- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

8.6 When to Still Use local()

Despite the existence of my, there are still three places where the local operator still shines. In fact, in these three places, you must use local instead of my.

  1. You need to give a global variable a temporary value, especially $_. The global variables, like @ARGV or the punctuation variables, must be localized with local(). This block reads in /etc/motd, and splits it up into chunks separated by lines of equal signs, which are placed in @Fields.
        local @ARGV = ("/etc/motd");
        local $/ = undef;
        local $_ = <>;  
        @Fields = split /^\s*=+\s*$/;
    It particular, it's important to localize $_ in any routine that assigns to it. Look out for implicit assignments in while conditionals.
  2. You need to create a local file or directory handle or a local function. A function that needs a filehandle of its own must use local() on a complete typeglob. This can be used to create new symbol table entries:
    sub ioqueue {
        local  (*READER, *WRITER);    # not my!
        pipe    (READER,  WRITER)     or die "pipe: $!";
        return (*READER, *WRITER);
    ($head, $tail) = ioqueue();
    See the Symbol module for a way to create anonymous symbol table entries. Because assignment of a reference to a typeglob creates an alias, this can be used to create what is effectively a local function, or at least, a local alias.
        local *grow = \&shrink; # only until this block exists
        grow();                 # really calls shrink()
        move();                 # if move() grow()s, it shrink()s too
    grow();                     # get the real grow() again
    See 15.7 for more about manipulating functions by name in this way.
  3. You want to temporarily change just one element of an array or hash. You can localize just one element of an aggregate. Usually this is done on dynamics:
        local $SIG{INT} = 'IGNORE';
        funct();                            # uninterruptible
    # interruptibility automatically restored here
    But it also works on lexically declared aggregates. Prior to 5.005, this operation could on occasion misbehave.
ISBN 9781906966027Perl Language Reference ManualSee the print edition