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;
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.