in reply to interleave (single shuffle)

Very nice trick. :-)

But no error checking though, it assumes that both arrays are of the same size, as many monks have pointed out already. (I know that you only did it for fun and in real life would not do without error checkings.) Personally I would favour a more conservative approach like the following -
use strict; use Data::Dumper; my @array1 = qw/ a b c d e /; my @array2 = qw/ 1 2 3 4 5 /; my $hash = build_hash(\@array1, \@array2); print Dumper($hash); # ----------------------------------------------------------- =pod =head1 FUNCTION sub build_hash ( \@array1, \@array2 ) =head1 SYNOPSIS my $hash = build_hash ( \@array1, \@array2 ); =head1 DESCRIPTION The function 'build_hash' takes 2 array references and returns reference to a hash. The hash is build by taking the elements from the first array as keys, and the corresponding elements from the second array as values. =cut # ----------------------------------------------------------- sub build_hash { my ($array1, $array2) = @_; return undef if $#$array1 ne $#$array2; # return \%{{map{$array1[$_]=>$array2[$_]}0..$#$array1}}; my %hash; # thanks ysth, yes I knew something was not right # with my map, I just couldn't remember the syntax # in the morning. :-) @hash{@$array1} = @$array2; return \%hash; }

Replies are listed 'Best First'.
Re: Re: interleave (single shuffle)
by ysth (Canon) on Nov 24, 2003 at 02:56 UTC
    The building a hash was just an example, not the point of the function. For the function in general, no error checking is possible because there are no error conditions. Every input has a well-defined output. For instance, interleave() returns an empty list, interleave('a'..'e') returns ('a','d','b','e','c').

    Given actual arrays, I would be more likely to say:

    %h = (); @h{@keys} = @values;