The solutions presented so far shuffle the lines as you go along. This is not good, although I can't recall where I read this. I thought it was on Perl Monks, but I can tease the thread out of the search box.

The flaw (as I understand it) is that lines appearing earlier in the file get selected more often than lines appearing later in the file, which leads to some failure to ensure that all possible shuffles are equally likely.

To do it right, you have to read all the lines in, and then apply a shuffling function to each entry. The canonical algorithm to do this is the Fisher-Yates shuffle.

You would want to do something like:

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

As it turns out, this is one of the rarer class of algorithms that exist where you must slurp the entire file into memory in order to process it.

update: I think MeowChow's and Screamer's solutions are ok, but they do have the effect of destroying the array. If all you need to do is print the lines then that is sufficient. Also, I'm not sure that creating repeated new arrays from the splice operation is wonderfully efficient. I haven't benchmarked it, it's just a gut feeling.

If you need to process the array in other ways, however, before writing it out then you have to push the spliced-out array elements onto another array, which means even more gymnastics going on behind the scenes.


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

In reply to Re: Mixing Up a Text File by grinder
in thread Mixing Up a Text File by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.