Reputation: 1067
If a key exists in a array, I want to print that key and its values from hash. Here is the code I wrote.
for($i=0;$i<@array.length;$i++)
{
if (exists $hash{$array[$i]})
{
print OUTPUT $array[$i],"\n";
}
}
From the above code, I am able to print keys. But I am not sure how to print values of that key.
Can someone help me?
Thanks
Upvotes: 1
Views: 17224
Reputation: 6566
Some alternative methods using hash slices:
foreach (@hash{@array}) { print OUTPUT "$_\n" if defined };
print OUTPUT join("\n",grep {defined} @hash{@array});
(For those who like golfing).
Upvotes: 1
Reputation: 263247
@array.length
is syntactically legal, but it's definitely not what you want.
@array
, in scalar context, gives you the number of elements in the array.
The length
function, with no argument, gives you the length of $_
.
The .
operator performs string concatenation.
So @array.length
takes the number of elements in @array
and the length of the string contained in $_
, treats them as strings, and joins them together. $i < ...
imposes a numeric context, so it's likely to be treated as a number -- but surely not the one you want. (If @array
has 15 elements and $_
happens to be 7 characters long, the number should be 157
, a meaningless value.)
The right way to compute the number of elements in @array
is just @array
in scalar context -- or, to make it more explicit, scalar @array
.
To answer your question, if $array[$i]
is a key, the corresponding value is $hash{$array[$i]}
.
But a C-style for
loop is not the cleanest way to traverse an array, especially if you only need the value, not the index, on each iteration.
foreach my $elem (@array) {
if (exists $hash{$elem}) {
print OUTPUT "$elem\n";
}
}
Upvotes: 6