my creates a new variable which is only valid inside a sub or block
Yes, to be more accurate: my creates a variable that exists till the end of the innermost enclosing block.
local uses the global var and saves its original value and you can give it a new value which is also only valid inside a sub or block
Yes, and the value exists till the innermost enclosing block is exited.
So..... both create a new variable.
How did you draw that conclusion? In your description of local you say it uses the global variable, and saves its original value, giving you a new value. That's correct - it uses the global variable.

The following is an easy reminder of the difference:

my creates a new variable; local creates a new value.

Note also that a myed variable isn't visible outside the block it's declared in, while a localized value is:

#!/usr/bin/perl use strict; use warnings; use vars '$global'; my $lexical; $global = 'outer'; $lexical = 'outer'; sub show { printf "\$global is '%s'; \$lexical is '%s'\n", $global, $lexical; } show; { local $global = 'inner'; my $lexical = 'inner'; show; } __END__ $global is 'outer'; $lexical is 'outer' $global is 'inner'; $lexical is 'outer'
Perl --((8:>*

In reply to Re: difference between my and local by Perl Mouse
in thread difference between my and local by jeanluca

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.