- 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.3.4 Localization of elements of composite types

It's also worth taking a moment to explain what happens when you localize a member of a composite type (i.e. an array or hash element). In this case, the element is localized by name. This means that when the scope of the local() ends, the saved value will be restored to the hash element whose key was named in the local(), or the array element whose index was named in the local(). If that element was deleted while the local() was in effect (e.g. by a delete() from a hash or a shift() of an array), it will spring back into existence, possibly extending an array and filling in the skipped elements with undef. For instance, if you say

%hash = ( 'This' => 'is', 'a' => 'test' );
@ary  = ( 0..5 );
{
     local($ary[5]) = 6;
     local($hash{'a'}) = 'drill';
     while (my $e = pop(@ary)) {
         print "$e . . .\n";
         last unless $e > 3;
     }
     if (@ary) {
         $hash{'only a'} = 'test';
         delete $hash{'a'};
     }
}
print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
print "The array has ",scalar(@ary)," elements: ",
      join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";

Perl will print

6 . . .
4 . . .
3 . . .
This is a test only a test.
The array has 6 elements: 0, 1, 2, undef, undef, 5

The behavior of local() on non-existent members of composite types is subject to change in future.

ISBN 9781906966027Perl Language Reference ManualSee the print edition