You want hash slices. They're so very tasty.
my %hash;
@hash{@keys} = @values;
Change the arrays to suit your needs.
japhy --
Perl and Regex Hacker | [reply] [d/l] |
Thanks for your replies, I didn't think I would get so many answers so fast!
I hope I will soon be able to answer some questions myself and so help other newbies like myself out...
Cheers,
Paz
| [reply] |
Use hash slices (briefly mentioned in perldata, but you can probably find more by searching PM for details:
my %hash;
@hash{ @array2 } = @array1;
Dr. Michael K. Neylon - mneylon-pm@masemware.com
||
"You've left the lens cap of your mind on again, Pinky" - The Brain
| [reply] [d/l] |
Thanks for your replies, I didn't think I would get so many answers so fast!
I hope I will soon be able to answer some questions myself and so help other newbies like myself out... Cheers, Paz
| [reply] |
The above code is very good, and will work for most situations. However, a problem arises if multiple elements of $ary1 have the same value--in which case the last such value assigned to the hash will stick. If this is not the desired effect, then more coding will be needed (and even this assumes that the two arrays have the same amount of elements, or in least @ary2 is larger). For your code, replace the else statement assignment with however you wish to deal with the data (now it is colon separated, but you may desire something else, or even a hash of arrays to store the multiple values).
for(0..$#ary1) {
unless (exists $hash{$ary1[$_]}) {
$hash{$ary1[$_]} = $ary2[$_]
} else {
$hash{$ary1[$_]} = "$hash{$ary1[$_]:$ary2[$_]"
}
}
| [reply] [d/l] |
#!/usr/bin/perl -w
use strict;
my @a = qw( 1 2 3 4 5 );
my @b = qw( a b c d e );
my %h = map { $a[$_] => $b[$_] } ( 0..$#a );
print "$_ => $h{$_}\n" foreach sort keys %h;
I'm still trying to find a way to do this without using indexes, though ;-)
Update: Yeah, the code japhy and Masem posted does exactly what I was looking for.
That's what happens when you're too far from your copy of The Camel Book ;-)
-mk | [reply] [d/l] |