bliako has asked for the wisdom of the Perl Monks concerning the following question:
I have a possibly bad habit to compact boring parts of my code like this:
if( exists($hash->{akey}) && defined($m=$hash->{akey}) && ($m==1) ){ $ +y = $m; ... } # don't trust $m here
But in this case it has unexpected results. This is the 1st part where a hash is constructed based on whether a key in another hash exists:
use strict; use warnings; use Data::Dumper; my %tests = ( 'a' => 10, 'b' => 20, ); my $m; # this seems to assign $m once and never bother to check again my %hash = ( 'b' => exists($tests{'b'}) && defined($m=$tests{'b'}) ? $m : 0, 'a' => exists($tests{'b'}) && defined($m=$tests{'a'}) ? $m : 0, ); print Dumper(\%hash); # this works as expected $m = 10; my %hash2 = ( '1' => $m++, '2' => $m++, '3' => $m++ ); print Dumper(\%hash2);
$VAR1 = { 'a' => 10, 'b' => 10 }; $VAR1 = { '1' => 10, '2' => 11, '3' => 12 };
Does anyone have an explanation? And is my habit bad?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Ternary Quizical behaviour?
by Eily (Monsignor) on Jul 10, 2020 at 12:33 UTC | |
Re: Ternary Quizical behaviour?
by roboticus (Chancellor) on Jul 10, 2020 at 12:51 UTC | |
by bliako (Monsignor) on Jul 10, 2020 at 17:33 UTC | |
Re: Ternary Quizical behaviour? (updated)
by LanX (Saint) on Jul 10, 2020 at 12:22 UTC | |
Re: Ternary Quizical behaviour?
by bliako (Monsignor) on Jul 10, 2020 at 17:33 UTC | |
by LanX (Saint) on Jul 10, 2020 at 17:44 UTC | |
by perlfan (Vicar) on Jul 10, 2020 at 20:41 UTC | |
by haukex (Archbishop) on Jul 10, 2020 at 21:18 UTC | |
by LanX (Saint) on Jul 10, 2020 at 21:51 UTC | |
by perlfan (Vicar) on Jul 10, 2020 at 20:35 UTC | |
Re: Ternary Quizical behaviour?
by karlgoethebier (Abbot) on Jul 11, 2020 at 20:28 UTC | |
Re: Ternary Quizical behaviour?
by perlfan (Vicar) on Jul 10, 2020 at 12:27 UTC | |
by Eily (Monsignor) on Jul 10, 2020 at 12:40 UTC | |
by perlfan (Vicar) on Jul 10, 2020 at 20:44 UTC | |
Re: Ternary Quizical behaviour?
by ikegami (Patriarch) on Jul 12, 2020 at 14:32 UTC | |
by bliako (Monsignor) on Jul 14, 2020 at 18:58 UTC | |
Re: Ternary Quizical behaviour?
by Anonymous Monk on Jul 10, 2020 at 12:34 UTC |
Back to
Seekers of Perl Wisdom