Re: accessing hash of arrays
by arun_kom (Monk) on Aug 21, 2009 at 07:26 UTC
|
If you can store the values of the hash in a list, then you can access its elements by their indices.
my %hash = ( 4 => [10, "mango"] ,
2 => [04, "banana"] ,
3 => [20, "apple"],
);
foreach (keys %hash){ print "$_: $hash{$_}[0]\n"; }
| [reply] [d/l] |
|
|
| [reply] |
Re: accessing hash of arrays
by jwkrahn (Abbot) on Aug 21, 2009 at 07:30 UTC
|
$ perl -le'
my %hash = ( 4 => [ 10, "mango" ], 2 => [ 04, "banana" ], 3 => [ 20, "
+apple" ] );
for my $array ( values %hash ) {
print $array->[ 0 ];
}
'
10
20
4
| [reply] [d/l] |
|
|
| [reply] |
|
|
| [reply] [d/l] |
Re: accessing hash of arrays
by tmharish (Friar) on Aug 21, 2009 at 07:22 UTC
|
Your hash structure does not look too clear to me.
But from what I understand it should be:
%hash = (
4 => \( 4, 'mango' )
...
)
If this is indeed the structure you can access 10,04, ... as follows:
@{ $hash[4] }[0] will give 10
@{ $hash[4] }[1] will give Mango
@{ $hash[2] }[0] will give 04
@{ $hash[3] }[0] will give 20
and so on ...
If you can tell us how you initialized your Hash, maybe things could be clearer. | [reply] [d/l] [select] |
|
|
4 => \( 4, 'mango' )
I guess you mean
4 => [4, 'mango']
?
--
Ronald Fischer <ynnor@mm.st>
| [reply] [d/l] |
Re: accessing hash of arrays
by sanku (Beadle) on Aug 21, 2009 at 09:49 UTC
|
hi,
You can able to get the values of 10,04,20 by using the following code. But before that one more thing is you have to mention the hash as we have declared in the below code i mean u have to mention the each and every hash element values as anonymous array.
my %hash = ( 4 => [10, "mango"] , 2 => [04, "banana"] , 3 => [20, "
+apple"] );
while(($key,$value) = each (%hash)){
print @$value[0];
}
| [reply] [d/l] |
Re: accessing hash of arrays
by AnomalousMonk (Archbishop) on Aug 21, 2009 at 16:54 UTC
|
>perl -wMstrict -le
"my $s;
$s = 04; print $s;
$s = 011; print $s;
"
4
9
| [reply] [d/l] [select] |
Re: accessing hash of arrays
by bichonfrise74 (Vicar) on Aug 21, 2009 at 16:15 UTC
|
There are more than one way to do this.
#!/usr/bin/perl
use strict;
my %hash = ( 4 => [10, "mango"] ,
2 => [04, "banana"] ,
3 => [20, "apple"],
);
for my $i ( keys %hash ) {
print "$i: $hash{$i}->[0]\n";
}
| [reply] [d/l] |