On Jan 24, 2005, at 9:09 AM, Louis Pouzin wrote:

I call a subroutine with a reference to a hash element.
In the subroutine I want to test if the element exists.

If you've taken a reference to the hash element, then it exists (after autovivification, if necessary). In the cat example, you're passing a hash reference and a key.


If so, I want to get the key and the value of the element.
I can't figure out the correct syntax.
So far I can only get the value. Could someone prompt me ?

It's been a few years, but off the top of my head...

#!perl -w
use strict; $\ = "\n";
my %H;
$H{one}{two}{three} = 'nut';
print exists $H{one}{two}{three}; # 1
cat(\$H{one}{two},'three');
dog(\$H{one}{two}{three});

sub cat{
        print $_[1]; # three
#       exists ${$_[0]}; # not a HASH element
#       exists ${$_[0]}{$_[1]}; # not a HASH reference
#       exists ${$_[0]}{"$_[1]"}; # not a HASH reference
#       exists $_[0]{"$_[1]"}; # not a HASH reference
}1;

My recollection is that $H{one}{two} is shorthand for $H{one}->{two}. That is, a hash only stores references, and a nested hash is stored in a containing hash by its reference. So $H{one}{two} evaluates to a reference to a hash with a single key 'three' and the value 'nut'. Therefore, \$H{one}{two} is a scalar reference, a reference to a reference to a hash. The correct syntax would be $(${$_[0]}}{$_[1]}, or just ${$_[0]}{$_[1]} if you drop the '\'.


sub dog{
        print ${$_[0]}; # nut
#       exists $_[0]; # not a HASH element
#       exists ${$_[0]}; # not a HASH element
#       exists ${${$_[0]}}; # not a HASH element
}1;

Again, you're passing a reference to a scalar. This time, the scalar is the string 'nut' instead of a hash reference. You can't test for existence because you've already subscripted the hash.


Josh

--
Joshua Juran
Metamage Software Creations - Mac Software and Consulting
http://www.metamage.com/

               * Creation at the highest state of the art *




Reply via email to