in reply to non-capture mode sometimes erases previous capture

This has nothing to do with non-capture mode.

The capture variables $1 and so on only hold the value of the last successful pattern match, and I guess the logic of non-capture mode only comes after the logic that resets $1 on a successful match. See perlvar for $1, where the behaviour of resetting $1 etc. is discussed.

Replies are listed 'Best First'.
Re^2: non-capture mode sometimes erases previous capture
by raygun (Scribe) on May 30, 2018 at 09:36 UTC
    Thanks, that explains why it works that way, but I still have my doubts whether that's the sanest approach. It just seems more useful to preserve any existing $1, $2, etc., when the user expressly says they don't want these variables populated. Looking at it another way, I can't think of a situation where the current behavior provides a benefit (though this could be a failure of my imagination), whereas I can think of situations where preserving the values is useful. Anyone agree, or am I off my rocker here?

      If you want to keep the captured bits, assign them to variables in your code, rather than relying on them being retained in global variables:

      my( $bit1, $bit2, $bit3 ) = /(..)(..)(..)/;

      Any code you call -- library routines etc. -- after you run the regex, but before you want to use its results, might also use the regex engine and overwrite those temporary global variables. So, don't rely on it.

      (Also, whether any of us agree with you or not, its been that way a very long time and isn't likely to change; so best get used to the idea :) )


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
      In the absence of evidence, opinion is indistinguishable from prejudice. Suck that fhit
        > Any code you call -- library routines etc. -- after you run the regex, but before you want to use its results, might also use the regex engine and overwrite those temporary global variables

        Invoking the regex engine in a different scope doesn't matter, the variables are properly dynamically scoped:

        #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; sub call_me { "xyz" =~ /(..)/; say $1; } "abc" =~ /(.)/; call_me(); say $1; # Still "a".

        Which doesn't mean I recommend using them.

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Even if these special variables did work the way you wish, BrowserUK's argument would still apply.
      Bill