If that's the best one can do to explain the difference between our and my, I'd have to say the Anon troll who's been going round lately proclaiming Perl is dead is right.

Well, it was meant partly as a joke. But laugh as much as you like, this is how I really understood our "back in the days..." so maybe it may benefit the OP as well.

Just for learning purposes I wondered: "how would I do (something like) the following

$ perl -lne '$c += () = /foo/g; END { print $c }'
if I (were mad enough to) put put it under strictures?"

Ok, I thought, if I were not a one-liner using -ln, then I'd do

my $c; while (<>) { $c += () = /foo/g; } print $c, "\n";
but a lexical variable wouldn't be appropriate for the previous situation, as it would be localized to the block realizing the body of the implicit while loop.

The obvious answer would be to fully qualify $c as $main::c. The remaining question was "anything more concise?" and the answer to this question would have been in the old days use vars; but I never really liked it because I had to pass the variables I wanted as strings and I knew it did symbol table manipulations, always conveying the impression of a dirty hack over which true syntactic sugar would have been preferrable. Eventually I realized that our was the syntactic sugar and the good shortcut I was looking for.

Hopefully what I learnt resulted to be useful also in other contexts and not only in knowing how to write strict-safe one-liners... ;-)


In reply to Re^5: difference between my and local by blazar
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.