How can I print the lines in STDIN in random order in Perl?

前端 未结 3 1795
遇见更好的自我
遇见更好的自我 2020-12-17 06:17

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

3条回答
  •  盖世英雄少女心
    2020-12-17 07:01

    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() {
        push @lines, $_;
        if (@lines == $bufsize) {
            print shuffle(@lines);
            undef @lines;
        }
    }
    print shuffle(@lines);
    

    Difference between this and the other solution:

    • Will not consume all the input and then randomize it (memory hog), but will randomize every $bufsize lines (not truly random and slow as a dog compared to the other option).
    • Uses a module which returns a new list instead of a in place editing Fisher - Yates implementation. They are interchangeable (except that you would have to separate the print from the shuffle). For more information type perldoc -q rand on your shell.

提交回复
热议问题