O'Reilly logo

Computer Science & Perl Programming by Jon Orwant

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 localisn’t entirely useless; there are cases in which mydoesn’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

mymakes most uses of localobsolete. 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 mythem; 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required