[prog] Perl vars and local

Douglas Hunter dug at plusthree.com
Wed Apr 20 04:37:19 EST 2005


Dan wrote:
> It seems to me that special Perl variables, especially $_, should be
> declared with "local" at the beginning of subroutines, but that I don't
> see people doing it very much.

Yes, not localizing perl's special globals can lead to nasty side effects.

> 
> It seems to me that the caller of a function shouldn't have to worry
> about global variables being modified. For example:
> 
>   while ( <> ) {
>     s/foo/bar/;
>     DoSomethingElse();    # Did this modify $_ ?
>     print;
>   }
> 

There is a discussion about this before the per-interpreter globals are 
introduced in pervar (http://perldoc.perl.org/perlvar.html).  People 
should heed the warnings there, but as you point out oftentimes do not.

> But, again, I don't see Perl programmers using "local" very much, even
> when they change $_. Are they using bad style, or is there something I'm
> not getting?
> 

Most probably they are not just using bad style, but introducing subtle 
bugs.  My rule of thumb is to use a named variable in place of $_ in 
anything except one liners and throw away scripts.

For instance, instead of:

while (<>) {
   do_stuff( $_ );
}

I would write:

while ( my $line = <> ) {
   do_stuff( $line );
}

Another rule of thumb is to localize other predefined globals to the 
smallest scope possible when setting their values.  For an example, see 
the early section on setting the input record separator ($/) in perlvar.

-- Douglas Hunter


More information about the Programming mailing list