Chapter 30. Seven Useful Uses of local
Mark Jason Dominus
In Scoping , I offered the advice “Always use my
; never use local
.” The most common use for both is to provide subroutines with private variables, and for this application you should always use my
, and never local
. But many readers (and TPJ’s tech editors) noted that local
isn’t entirely useless; there are cases in which my
doesn’t work, or doesn’t do what you want. I promised a followup article on useful uses for local
; here they are.
1. Special Variables
my
makes most uses of local
obsolete. So it’s not surprising that the most common useful uses of local
arise because of peculiar cases where my
happens to be illegal.
The most important examples are the punctuation variables such as $", $/, $^W
, and $_. Long ago, Larry Wall decided it would be too confusing if you could my
them; they’re exempt from the normal package scheme for the same reason. If you want to change them, but have the change apply to only part of the program, you’ll have to use local
.
As an example of where this might be useful, let’s consider a function whose job is to read in an entire file and return its contents as a single string:
sub getfile { my $filename = shift; open F, "< $filename" or die "Couldn't open `$filename': $!"; my $contents = ''; while (<F>) { $contents .= $_;} } close F; return $contents; }
This is inefficient, because the <F>
operator makes Perl go to all the trouble of breaking the file into lines and returning them one at a time, and then ...
Get Computer Science & Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.