in reply to Best Hash Practices?
2. I don't know of any way to cause a hash key's value to be "non-existant". There is a thing called "undefined", undef. But undef is not the same as "non-existant". undef means exists but I don't know what the value is.
3. When you test a hash key, you are testing the value of the key. It can be true or false. false values are: "undef","",'',0.
4. If a hash key value "exists" then it can have any one of the 4 values above. Update: well of course, then it can also have some other string or numeric value. The above 4 things, which are actually only 3 things, undef, null string and zero are all the same "false" value in a logical expression.
5. If a hash key value is "defined", then there only 3 possibilities. Update: well "" and '' are the same once the string is interpreted.
#!/usr/bin/perl -w use strict; use Data::Dumper; my %hash = ('a' => 2, 'b' => 3, 'c' => undef); print Dumper (\%hash); if (exists ($hash{'c'}) ) {print "key c exists\n"} else {print "key c does not exist\n"}; print Dumper (\%hash); if ( defined ($hash{'c'}) ) {print "key c defined\n"} else {print "key c not defined\n"}; if (exists ($hash{'d'}) ) {print "key d exists\n"} else {print "key d does not exist\n"}; #note that undef,"",'' and 0 all evaluate to "false" #play with c value above and run this code #you can call defined($xxx) to figure out the difference #between a false value from "",'',0 and undef. if (my $x = $hash{'c'}) {print "c has value $x\n"} else {print "c has value,\"\",0 or undef\n"}; if (my $x = $hash{'b'}) {print "b has value $x\n"} else {print "b has no value\n"}; __END__ $VAR1 = { 'c' => undef, 'a' => 2, 'b' => 3 }; key c exists $VAR1 = { 'c' => undef, 'a' => 2, 'b' => 3 }; key c not defined key d does not exist c has no value b has value 3
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Best Hash Practices?
by ikegami (Patriarch) on Oct 09, 2009 at 03:36 UTC | |
by Marshall (Canon) on Oct 09, 2009 at 04:10 UTC | |
by ikegami (Patriarch) on Oct 09, 2009 at 05:05 UTC | |
by Marshall (Canon) on Oct 09, 2009 at 05:25 UTC | |
by ikegami (Patriarch) on Oct 09, 2009 at 06:47 UTC | |
| |
Re^2: Best Hash Practices?
by gloryhack (Deacon) on Oct 09, 2009 at 02:56 UTC | |
by Marshall (Canon) on Oct 09, 2009 at 04:43 UTC |