You don't need clutter just to use a variable. Remember that a do block returns the last evaluated expression. In this example, I assign that result to @memories, which puts the matches in list context so they return the parts they remembered as a list.

$_ = 'abcdefghijk'; foreach my $left ( 0 .. 1 ) { my @memories = do { if( $left ) { /ab(..)ef/ } else { /fg(..)jk/ } }; print "Left $left: caught @memories\n" }

Once I have the memories in the array, I can easily pull out any element that I like. If the match fails, @memories is empty. I don't have to deal with a lot of gymnastics to figure out is the match succeeded. Without knowing that the match suceeded, you shouldn't use any of the number variables ($1, $2, and so on).

Remember that $1 and so on are package variables, and that they persist until the next successful pattern match. It doesn't have anything to do with lexical scope. Actually, perlvar says:

$<digits> Contains the subpattern from the corresponding set of capturing parentheses from the last pattern match, not counting patterns matched in nested blocks that have been exited already. (Mnemonic: like \digits.) These variables are all read-only and dynamically scoped to the current BLOCK.
--
brian d foy <brian@stonehenge.com>
Subscribe to The Perl Review

In reply to Re: ?: and saving backreferences by brian_d_foy
in thread ?: and saving backreferences by throop

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.