使用Perl随机化3行以在CGI中显示

时间:2013-10-02 16:16:43

标签: perl cgi

我正在尝试编写一个CGI脚本,它将采用三行文本并随机化它们。每次查看网页时,这三行将每次以不同的顺序依次出现。我该怎么做以及代码是什么?

2 个答案:

答案 0 :(得分:4)

perldoc -q "random line"
Found in D:\sb\perl\lib\perlfaq5.pod
  How do I select a random line from a file?
    Short of loading the file into a database or pre-indexing the lines in
    the file, there are a couple of things that you can do.

    Here's a reservoir-sampling algorithm from the Camel Book:

        srand;
        rand($.) < 1 && ($line = $_) while <>;

    This has a significant advantage in space over reading the whole file
    in. You can find a proof of this method in *The Art of Computer
    Programming*, Volume 2, Section 3.4.2, by Donald E. Knuth.

    You can use the File::Random module which provides a function for that
    algorithm:

        use File::Random qw/random_line/;
        my $line = random_line($filename);

    Another way is to use the Tie::File module, which treats the entire file
    as an array. Simply access a random array element.

perldoc -q shuffle
Found in D:\sb\perl\lib\perlfaq4.pod
  How do I shuffle an array randomly?
    If you either have Perl 5.8.0 or later installed, or if you have
    Scalar-List-Utils 1.03 or later installed, you can say:

        use List::Util 'shuffle';

        @shuffled = shuffle(@list);

    If not, you can use a Fisher-Yates shuffle.

        sub fisher_yates_shuffle {
            my $deck = shift;  # $deck is a reference to an array
            return unless @$deck; # must not be empty!

            my $i = @$deck;
            while (--$i) {
                my $j = int rand ($i+1);
                @$deck[$i,$j] = @$deck[$j,$i];
            }
        }

答案 1 :(得分:2)

use List::Util qw( shuffle );
@lines = shuffle(@lines);