如何在Perl中以随机顺序在STDIN中打印行? [英] How can I print the lines in STDIN in random order in Perl?

查看:113
本文介绍了如何在Perl中以随机顺序在STDIN中打印行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做 sort(1)的逆运算:将每个随机Perl中 stdin stdout 的行.

I want to do the inverse of sort(1) : randomize every line of stdin to stdout in Perl.

推荐答案

我敢打赌,真正的Perl黑客会撕裂这一点,但不管怎么说,这还是可行的.

I bet real Perl hackers will tear this apart, but here it goes nonetheless.

use strict;
use warnings;
use List::Util 'shuffle';

my @lines = ();
my $bufsize = 512;
while(<STDIN>) {
    push @lines, $_;
    if (@lines == $bufsize) {
        print shuffle(@lines);
        undef @lines;
    }
}
print shuffle(@lines);

此解决方案与其他解决方案之间的区别:

Difference between this and the other solution:

  • 不会消耗所有输入,然后将其随机化(内存猪),但将随机化每条$ bufsize的行(与其他选择相比,它并不是真正的随机且慢).
  • 使用返回新列表的模块,而不是就地编辑Fisher-Yates实现的模块.它们是可互换的(除非您必须将打印与随机播放分开).有关更多信息,请在您的shell上键入perldoc -q rand.

这篇关于如何在Perl中以随机顺序在STDIN中打印行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆