If your key contains an array, the hash value is a reference to that array. Testing with ref should tell you what sort of value it is.
foreach my $key (keys %hash) {
$value = $hash{$key};
# Perhaps a dispatch table for this would be better...
if (ref($value) eq q{ARRAY}) {
# Do whatever you you feel like doing with your array
}
elsif (ref($value) eq q{}) {
# Scalar, handle as you wish
}
else {
# None of the above types; make sure you know
}
}
The different sorts of values (see perlfunc for ref and its use) allow you to handle more than scalar (strings) or arrays. It may pay to know if your data contains something unexpected instead of just trying to parse it.
If handling multiple types, a dispatch table allows for easier extension. Handling the 'other data type' case is different, but a simple defined() usually does it for me.
A caveat to the above is probably if you have an object (and a reference) that you blessed into the ARRAY class. I suspect that's why ikegami above mentioned Scalar::Util's reftype().
Edit: Fixed the scalar case, since ref() returns an empty string for a non-reference (and SCALAR for a reference to a scalar value). Thanks to a kind monk paying attention.
|