Here's a neat use of Perl's aliasing of @_.

#! perl -slw use strict; ## Shuffle an array in place; sub shuffle { my $ref = @_ == 1 ? $_[ 0 ] : \@_; my $n = @$ref; for( 0 .. $#$ref ) { my $p = $_ + rand( $n-- ); my $t = $ref->[ $p ]; $ref->[ $p ] = $ref->[ $_ ]; $ref->[ $_ ] = $t; } return unless defined wantarray; return wantarray ? @{ $ref } : $ref; } my @a = 'a' .. 'c'; my @b = 1 .. 4; my @c = 'A' .. 'E'; shuffle( @a, @b, @c );; print "A:= [ @a ]\nB:= [ @b ]\nC:= [ @c ]"; __END__ c:\test>junk8 A:= [ c b D ] B:= [ 4 A 3 B ] C:= [ E 2 a 1 C ]

Notice how after the shuffle, the elements of the arrays have been intermixed in the 3 arrays, but each knows how big it is. This is because @_ gets aliased to the elements of all 3 arrays.

Thus, by shuffling @_ within the sub, we are shuffling the elements of all 3 arrays at the same time.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

In reply to Re: Randomize elements among several arrays, while maintaining original array sizes. by BrowserUk
in thread Randomize elements among several arrays, while maintaining original array sizes. by BioNrd

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.