Hello, wise and compassionate Monks:

I have a situation in my code where I'm identifying data using patterns, and sometimes the patterns are not matched. What is happening to me is that when a pattern does not match, a previous value is being kept and used. According to perldoc perlre and Programming Perl, these values are not reset until the end of the current context block or the next successful pattern match.

I've managed to fix the problem using an artificial block, like this example, but I'm wondering if there's a better way.

if (1) # extra if resets $1 backreference { $filename =~ /^([^_]+)_([^_]+)/; $rs[0] = $1; $rs[1] = $2; } # end of extra if (1) open (TESTF, "<./$filename") or die "open\n"; # now process lines which may or may not have matches while (my $line = <TESTF>) { chomp $line; if ($line =~ /^\x7CTARGET/) { my ( $kw, $dtarget, $kw2, $dorient ) = split( /\x7C/, $line ); $dorient =~ /^([^_]+)_/; $rs[2] = $1; if (!defined($rs[2])) { $rs[2] = 'nocount'; } } elsif (...) { ... } } # test @rs values
My problem was that if $dorient doesn't have SOMETHING_, $rs2 was set to the previous value of $1. In this particular case, I could sometimes get away with using /^(^_+)/ as the pattern, but I'm looking for the more general solution here.

UPDATE: made example more clear

Don Wilde
"There's more than one level to any answer."

In reply to resetting Perl RegEx backreferences by samizdat

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.