in reply to Re^2: scope of my $x in if statements
in thread scope of my $x in if statements

So?

Replies are listed 'Best First'.
Re^4: scope of my $x in if statements
by ig (Vicar) on May 08, 2009 at 02:05 UTC

    Just a nit, unless one is concerned that this $x should be out of scope after the end of the if block. The outer scope could have its own $x, for example.

      Limiting the scope to the if doesn't limit the lifetime of the value for destruction purposes (see if(my) scope), and if the outer scope already has an $x, you'll get a warning (easily fixed by using curlies or the other alternative I posted).

        Agreed, except that the warning isn't always produced, depending on the surrounding scopes.

        use strict; use warnings; my $x = "outermost x"; print "alternative 1\n"; if( e() ) { my $x = f(); if( $x and g($x) ) { print "inside the inner if \$x = $x\n"; } print "after the inner if \$x = $x\n"; } print "after the outer if \$x = $x\n"; print "\nalternative 2\n"; if( e() ) { if( my $x = f() ) { if( g($x) ) { print "inside the inner if \$x = $x\n"; } } print "after the inner if \$x = $x\n"; } print "after the outer if \$x = $x\n"; sub e { return "sub e here"; } sub f { return "sub f here"; } sub g { return "sub g here"; } __END__ alternative 1 inside the inner if $x = sub f here after the inner if $x = sub f here after the outer if $x = outermost x alternative 2 inside the inner if $x = sub f here after the inner if $x = outermost x after the outer if $x = outermost x