glendeni has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Defined test creates non-empty hash value
by choroba (Cardinal) on Jun 12, 2024 at 16:40 UTC | |
by glendeni (Sexton) on Jun 12, 2024 at 23:54 UTC | |
by cavac (Prior) on Jun 13, 2024 at 10:00 UTC | |
by LanX (Saint) on Jun 14, 2024 at 12:53 UTC | |
by LanX (Saint) on Jun 15, 2024 at 13:48 UTC | |
|
Re: Defined test creates non-empty hash value
by sectokia (Friar) on Jun 17, 2024 at 01:32 UTC | |
by etj (Priest) on Jun 17, 2024 at 13:58 UTC |