What's the best way to clear regex matching variables?

vol7ron picture vol7ron · Apr 18, 2012 · Viewed 10.1k times · Source

What's the best way to clear/reset all regex matching variables?

  • Example how $1 isn't reset between regex operations and uses the most recent match:

    $_="this is the man that made the new year rumble"; 
    / (is) /; 
    / (isnt) /; 
    say $1;          # outputs "is"
    
  • Example how this may be problematic when working with loops:

    foreach (...){
       /($some_value)/;
       &doSomething($1) if $1;
    }
    

Update: I didn't think I'd need to do this, but Example-2 is only an example. This question is about resetting matching variables, not the best way to implement them.

Regardless, originally my coding style was more inline with being explicit and using if-blocks. After coming back to this (Example2) now, it is much more concise in reading many lines of code, I'd find this syntax faster to comprehend.

Answer

Mark Reed picture Mark Reed · Apr 18, 2012

You should use the return from the match, not the state of the group vars.

foreach (...) {
    doSomething($1) if /($some_value)/;
}

$1, etc. are only guaranteed to reflect the most recent match if the match succeeds. You shouldn't be looking at them other than right after a successful match.