There is however another "layer" of complexity to this question that you are probably not aware of....
When testing for the existence of some value in a 2D hash, Perl will "autovivify" the first dimension(s) if it(they) doesn't exist already. The code below demonstrates this behavior. This can lead to some side-effects and strange results later.
This statement:
creates the entire multi-dimensional key and assigns it the value of '' if it wasn't already defined. This '//=' operator is specific to Perl. It is like ||= except that it tests for "defined-ness" instead of "truth-ness". Whether or not this is a "good thing" or "not" depends upon the application.$var = $vxdg{$node}{$disk} //= '';
I'm just suggesting that you should be aware of what happens when testing for existence or "defined-ness" of multi-dimensional hash array values.
#!/usr/bin/perl -w use strict; use Data::Dumper; my %vxdg; my $var; my ($node,$disk) = (3, "C:"); print "node= $node disk=$disk\n"; print "orignal hash is:", Dumper \%vxdg; print "\$var is: \"", (defined $var) ? $var : "undefined", "\"","\n"; $var = exists $vxdg{$node}{$disk} ? $vxdg{$node}{$disk} : ''; print "the hash is now...after checking for",'$vxdg{$node}{$disk}:', "\n", Dumper \%vxdg; print "\$var is: \"", (defined $var) ? $var : "undefined", "\"","\n"; print "\n***Starting over..***\n"; %vxdg=(); $var=undef; print "orignal hash is:", Dumper \%vxdg; $var = $vxdg{$node}{$disk} //= ''; print "the hash is now...:", "\n", Dumper \%vxdg; print "\$var is: \"", (defined $var) ? $var : "undefined", "\"","\n"; __END__ node= 3 disk=C: orignal hash is:$VAR1 = {}; $var is: "undefined" the hash is now...after checking for$vxdg{$node}{$disk}: $VAR1 = { '3' => {} }; $var is: "" ***Starting over..*** orignal hash is:$VAR1 = {}; the hash is now...: $VAR1 = { '3' => { 'C:' => '' } }; $var is: ""
In reply to Re^5: Short form (ternary) if else
by Marshall
in thread Short form (ternary) if else
by gg48gg
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |