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

My thought was since it was defined in each of the if parts that it would be difined after the if statements... Maybe i don't understand what you mean?

Replies are listed 'Best First'.
Re^3: Stupid If Question
by ikegami (Patriarch) on Aug 18, 2009 at 21:16 UTC

    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; }
Re^3: Stupid If Question
by biohisham (Priest) on Aug 18, 2009 at 21:15 UTC
    Since the variable is used in three different places you can declare it right at the top, and hence the scoping of it would be such that it is available to the entire code. When you declare a variable inside blocks (i.e. {} ) the scope of that variable determines its visibility only inside that block and within it.

    use strict; my $zipexe;
    thumbs-up for using "strict"...keep up the good work :)

    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.
Re^3: Stupid If Question
by ikegami (Patriarch) on Aug 18, 2009 at 21:18 UTC

    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; }
      (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.