On Tue, Mar 17, 2009 at 09:30, Dermot <paik...@googlemail.com> wrote:
snip
> if ($x{$x})  inspects the key's value, not simply the existence of a key?
snip

Yes, but beware of autovivification (i.e. the creating of keys by
trying to look at their values).  You are safe with this simple case,
but when dealing with HoHs or other complex data structures you can
accidentally create keys.  Always use exists on each level but the
last before examining the value of a deeper level.  Also, it tests the
value not the definededness, so if $x{$x} was 0 or '' it would be
false even though it was defined.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my %h = (
        english => [ qw/zero one two three/ ],
        latin   => [ qw/zerum uno duos tres/ ],
);
print Dumper \%h;

#wrong
unless (defined $h{german}[0]) {
        print "german 0 is not set\n";
}

#right
unless (exists $h{chinese} and exists $h{chinese}{mandarin} and
defined $h{chinese}{mandarin}[0]) {
        print "mandarin chinese 0 is not set\n";
}
print Dumper \%h;

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to