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

i got the folowing function from the online version of the perl cookbook (recipe 4.17) so i was very suprised when it gave me an error

sub fisher_yates_shuffle { my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } }

when the function is called with

fisher_yates_shuffle( \@array );

as recommended in the recipe i get the error "too many arguments for main::fisher_yates_shuffle"

Code tags and formatting added to match original intent, by davido.

Replies are listed 'Best First'.
Re: shuffle array (in place)
by tlm (Prior) on May 11, 2005 at 22:35 UTC

    You probably did not really define the function as you posted it, but rather like this:

    sub fisher_yates_shuffle () { ... }
    ...which tells perl (via an empty prototype) that the function should take no arguments. (Prototypes are described in perlsub). Just remove the () after the sub's name and it will work fine.

    the lowliest monk

Re: shuffle array (in place)
by borisz (Canon) on May 11, 2005 at 22:34 UTC
    here is a working version:
    sub fisher_yates_shuffle { my $deck = shift; # $deck is a reference to an array my $i = @$deck; while ( $i-- ) { my $j = int rand( $i + 1 ); @$deck[ $i, $j ] = @$deck[ $j, $i ]; } } my @aa = qw/a b c d e f/; fisher_yates_shuffle( \@aa );
    for more read perldoc -q shuffle.
    Boris