in reply to Re: Use variable outside if statement
in thread Use variable outside if statement

That's a very good point. And in situations where a seperate sub may be inconvenient, an enclosing lexical block can be helpful:

use strict; use warnings; my $var = 10; { my $var = 20; print $var, "\n"; } print $var, "\n"; __OUTPUT__ 20 10

...just a quick demonstration of using {...} blocks to limit scope and protect variables of broader scope.

Perl is great at providing mechanisms for lexical scoping: file-based scope, package scope, block scope, subroutine scope, as well as other mechanisms such as do{...}; and eval. It can be a tricky maze to wander at first, but definately flexible.

Perl programmers are lucky in that they can decide just how complex or simple they want their scoping and modularization to be.


Dave

Replies are listed 'Best First'.
Re: Re: Re: Use variable outside if statement
by skyknight (Hermit) on Dec 18, 2003 at 16:33 UTC
    That depends on whether you are the guru, able to exploit a rich syntax to create compact and elegant code, or a novice struggling to comprehend what may look like line noise to you. Perl's expressivity as a language can be a wonderful thing, but it comes as a dangerous double edged sword. What is and is not appropriate to write depends on your target audience. Reckless and excessive use of some of Perl's more arcane functionality is what often gets Perl branded as a write only language amongst the unenlightened, and also causes Perl to lean toward unmanageability when code bases grow large.