I like your suggestion to use the ternary operator. In fact, it makes more sense than the high-precedence logical operator approach you outline above. The logical approach relies on short-circuit effects to work, and may not be obvious to future maintainers. The ternary operator is being used in its normal mode.
Another issue with the logical approach is that when the condition is false, the value of $x becomes whatever scalar the condition evaluates to. This could lead to unexpected behavior where the condition may evaluate to an otherwise legal value for $x.
my $y = 0; # ... Much code; my @list = (); # ... Much code my $x = @list && $y; # if $x is 0, did it come from @list or $y?
If the OP wants to do a conditional assignment and declaration on one line, the following is, IMHO, unambiguously the way to go.
sub sub1 { # ... my $x = <some condition> ? $y : undef; # ... }
TGI says moo
In reply to Re^2: "if" in a my declaration statement causes problem
by TGI
in thread "if" in a my declaration statement causes problem
by ganeshk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |