It is important to understand the differences between my and local; just blindly only using my is little better than blindly only using local. Fundamentally, they're useful for different purposes, because they do different things. I like to think of my as a namespace qualifier that prevents collisions with anything outside the current block (or file). On the other hand, local has nothing whatsoever to do with namespaces but rather with time; I like to think of it as temporary assignment. It temporarily changes the value of a particular variable but allows it to revert back to its former value later.

The upshot of this is that you can use local to change *somebody else's* variable, temporarily. For instance, you can local a package-scoped variable from a module you're using, or a global special variable like $_ or $/ or whatnot. By doing this you can change the behavior of code that uses that variable -- not just your own code, but also any code that you call (e.g., by using local on $/ you can change the way the diamond operator (which is not, strictly speaking, your code) works when you call it, but allow its behavior to revert back to "normal" later when you're done). This is tremendously useful, but it's also completely different from anything you would do with my.

The only thing my and local have in common is that they both have to do with variable scope.


In reply to my versus local: apples and oranges by jonadab
in thread global $_ behavior by verdemar

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.