in reply to Difference my and local

The difference is that a local replaces a global in the current block and in any subroutines that are called from the current block. my is only in effect for the enclosing block (or package thanks revdiablo or file).
use strict; use warnings; our ($x, $y) = ('global X', 'global Y'); example(); sub example { local $x; my $y; $x = 'changed local'; $y = 'changed my'; example2(); } sub example2 { print "X: $x, Y: $y\n"; }
example2 will print the $x that is local to example, but the global $y.

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Difference my and local
by strat (Canon) on May 25, 2005 at 07:01 UTC

    Well, as a rule of thumb: use my everywhere, and only if perl complains about, think about using local (e.g. with build in perl variables)

    With local, you can also localize parts of datastructures, e.g.

    use warnings; use strict; use vars qw(@array); @array = 1..20; print "BEFORE: @array\n"; &TestSub(); print "AFTER: @array\n"; sub TestSub { local @array[4..10]; @array[4..11] = 104..111; print "INSIDE: @array\n"; }
    which outputs something like:
    BEFORE: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 INSIDE: 1 2 3 4 104 105 106 107 108 109 110 111 13 14 15 16 17 18 19 2 +0 AFTER: 1 2 3 4 5 6 7 8 9 10 11 111 13 14 15 16 17 18 19 20

    beware that 111 is not "localized" and so the change is global.

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"