in reply to Re^2: Stupid If Question
in thread Stupid If Question

Three variables were defined, one in each block. (Blocks which aren't even mutually exclusive, I might add.) A fourth variable doesn't magically become defined elsewhere as a result. I believe you want

my $var; if (...) { $var = ...; } elsif (...) { $var = ...; } else { die; }

Replies are listed 'Best First'.
Re^4: Stupid If Question
by ig (Vicar) on Aug 19, 2009 at 07:49 UTC
    (Blocks which aren't even mutually exclusive, I might add.)

    Initially I thought you meant that the blocks aren't mutually exclusive from the perspective of lexical variable scoping. It has never occurred to me that an if statement might create a single scope, rather than one for each branch. Testing seems to confirm my assumption that each branch is a separate scope.

    #!/usr/local/bin/perl use strict; use warnings; foreach (1..3) { if($_ < 2) { my $x = 1; print "$_ < 2, \$x = $x\n"; } else { print "$_ >= 2, \$x = $x\n"; } } __END__ Global symbol "$x" requires explicit package name at ./test.pl line 10 +. Execution of ./test.pl aborted due to compilation errors.

    Then it occurred to me that you probably mean that the conditions of the two if statements are not mutually exclusive - a possible problem with program logic but not affecting variable scope.

      Then it occurred to me that you probably mean that the conditions of the two if statements are not mutually exclusive

      Correct.