in reply to "if" in a my declaration statement causes problem

Another possibility, if you still wanted it on one line, would be:

sub sub1 { #... my $x = ( <some condition> ) && $y; #... }

This way, if the condition ended up false, you'd wind up with some false value (although not necessarily undef) in your variable. You could do my $x = ( <some condition> ) ? $y : undef; if you need $x to default to undef, but I'd say Siddartha's solution looks tidier for that case.

Replies are listed 'Best First'.
Re^2: "if" in a my declaration statement causes problem
by TGI (Parson) on Feb 21, 2006 at 18:21 UTC

    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