Stamp_Guy has asked for the wisdom of the Perl Monks concerning the following question:

I've got a question: What is a quick way to scramble the order of some lines in an array? Say I have a 25 line pipe deliminated database. I want the lines to be scrambled, but their contents not to change. Also, in a CGI program, how might I make it so someone could choose which line goes where (ie: sort it themselves by entering a number in a text field)?

Replies are listed 'Best First'.
Re: Reordering arrays
by Fastolfe (Vicar) on Jan 14, 2001 at 22:42 UTC
    See How do I shuffle an array?.
    @lines = <IN>; shuffle(@lines); print OUT @lines; # or if 'shuffle' returns the shuffled list print OUT shuffle(<IN>);
    As far as moving elements from one place to another, just move them around, or use splice if you need some more "serious" movements:
    ($lines[param('from')], $lines[param('to')]) = ($lines[param('to')], $lines[param('from')]);
Re: Reordering arrays
by lhoward (Vicar) on Jan 14, 2001 at 22:42 UTC
Re: Reordering arrays
by Kanji (Parson) on Jan 14, 2001 at 22:51 UTC

    To randomly re-order on-the-fly, this should do...

    my @lines = <FILE>; print splice( @lines, rand @lines, 1 ) while @lines;

    For arbritraty ordering (as in supplied via user input), if you can be assured of having the right number of line orderings and making sure you count from 0 not 1, then you can do an array splice ...

    @order = qw( 17 4 23 7 12 19 8 0 16 9 21 1 14 15 6 11 20 3 2 24 5 13 18 10 22 ); print @lines[ @order ]

    ... assuming you replaced qw() with your CGI input.

        --k.


A reply falls below the community's threshold of quality. You may see it by logging in.