in reply to Arrow Operator Question
G'day sectokia,
[Note: $a (and $b) are special variables; it's best to only use these for their intended purposes to avoid unexpected side effects; I've replaced $a with $h in the code below. Also, '//undef' is completely superfluous: if the LHS is undef, use undef instead. :-)]
See Autovivification and Arrow Notation in perlref.
Perl will autovivify as needed. It requires 'c' to check for 'd', so that key is autovivified. The 'd' key either exists and has a value or it doesn't exist and the value is undef: no autovivification is needed here.
You can use exists() to check for 'c'; only attempting to get a value for 'd' if 'c' exists. That can become unwieldy when there are multiple levels of keys; if you think autovivification is a problem, simply allow it then delete() afterwards.
The following code has examples which demonstrate these points.
$ perl -E ' use Data::Dump; { say "*** Autovivification"; my $h = { b => {} }; dd $h; my $f = $h->{b}{c}; say $f // "undefined"; dd $h; my $g = $h->{b}{c}{d}; say $g // "undefined"; dd $h; } { say "*** No autovivification"; my $h = { b => {} }; dd $h; my $f = $h->{b}{c}; say $f // "undefined"; dd $h; my $g = exists $h->{b}{c} ? $h->{b}{c}{d} : undef; say $g // "undefined"; dd $h; } { say "*** Autovivify then delete"; my $h = { b => {} }; dd $h; my $f = $h->{b}{c}{x}{y}{z}; say $f // "undefined"; dd $h; delete $h->{b}{c}; dd $h; } '
Output:
*** Autovivification { b => {} } undefined { b => {} } undefined { b => { c => {} } } *** No autovivification { b => {} } undefined { b => {} } undefined { b => {} } *** Autovivify then delete { b => {} } undefined { b => { c => { x => { y => {} } } } } { b => {} }
— Ken
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Arrow Operator Question
by BillKSmith (Monsignor) on Mar 27, 2023 at 14:24 UTC | |
by hv (Prior) on Mar 27, 2023 at 17:28 UTC | |
by BillKSmith (Monsignor) on Mar 28, 2023 at 18:07 UTC | |
by kcott (Archbishop) on Mar 27, 2023 at 16:57 UTC | |
by BillKSmith (Monsignor) on Mar 28, 2023 at 18:02 UTC | |
Re^2: Arrow Operator Question
by sectokia (Friar) on Mar 27, 2023 at 08:41 UTC | |
by kcott (Archbishop) on Mar 27, 2023 at 10:14 UTC |