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
@array.lengthis syntactically legal, but it’s definitely not what you want.@array, in scalar context, gives you the number of elements in the array.The
lengthfunction, with no argument, gives you the length of$_.The
.operator performs string concatenation.So
@array.lengthtakes the number of elements in@arrayand 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@arrayhas 15 elements and$_happens to be 7 characters long, the number should be157, a meaningless value.)The right way to compute the number of elements in
@arrayis just@arrayin 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
forloop is not the cleanest way to traverse an array, especially if you only need the value, not the index, on each iteration.