I'd always assumed tests could never _create_ anything - they were just tests that either succeeded or failed, never actually affecting variables solely by being used. So was very surprised to recently find that use of the 'defined' test on a hash of arrays ala
defined $hash{$name}[$integer]
actually _created_ an empty $hash{$name} if $hash{$name} is non-existent, so is thereafter not non-existent.
Example code:
my %hash = ( "A" => [ 1,2 ] ) ; if ( exists $hash{"B"} ) { say "This will NOT print" ; } if ( defined $hash{"B"}[1] ) { say "This will NOT print" ; } if ( exists $hash{"B"} ) { say "This WILL print" ; }
So the "correct" test for existence of an array element in a hash of arrays should be
if ( exists $hash{"B"} && defined $hash{"B"}[1] )
Would appreciate comments by those with deeper knowledge of perl than I, since I can't see how such creation is in any way beneficial - rather it can introduce problems into a script, since the first use of such a test will fail but a second same test will later succeed without the programmer intending (or expecting) any such change.
IMHO a test should succed, or fail, or throw an error - period.FYI the same occurs for a test ala "$#{$hash{"B"}} > -1".
Background: Have used perl regularly since 1998 so am experienced in perl, but never dug too deeply into it.
In reply to Defined test creates non-empty hash value by glendeni
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |