Cristoforo has asked for the wisdom of the Perl Monks concerning the following question:

In working with the code from this node, Re: regex persistence of matches, I found incorrect (?) results for the values for the @+ and @_ arrays. The values of the overall match, (index 0), should be the same as the values for the one captured group, (index 1), but they aren't. Just wondering why this happened.
#!/usr/bin/perl use strict; use warnings; $_ = "foobar1"; if (/o(.*)a/) { for my $i (0..$#+) { print substr($_, $-[$i], $+[$i] - $-[$i]), "\n"; } } OUTPUT C:\perlp>perl t1.pl ooba ob C:\perlp>

Chris

Replies are listed 'Best First'.
Re: @- and @+ question
by Juerd (Abbot) on Jun 19, 2007 at 19:15 UTC

    The values of the overall match, (index 0), should be the same as the values for the one captured group, (index 1),

    Only if the first paren group is around the entire regex, which it isn't. Index 0 describes $&, 1 does $1, 2 does $2, etcetera, only without actually using those globals.

    Juerd # { site => 'juerd.nl', do_not_use => 'spamtrap', perl6_server => 'feather' }

      While im pretty sure you know this, ill mention it for other readers:

      @- and @+ are actually thin wrappers around the way that Perl internally tracks where matches and capture buffers start and stop. The variables $& and $1 and friends actually are ties that combine the data in @- and @+ with a copy of the string matched against to produce the magic variables. If you have ever wondered why @- and @+ exist and why they are such strange things its because they are really just tied variables that wrap C arrays*. Larry is on record saying that he considers them a bad interface because of this.

      * in Perl 5.9.4 Nicholas Clark merged the two arrays into a single array of structs containing two STRLEN's (long integers).

      ---
      $world=~s/war/peace/g

        Actually, I had no idea. Thanks for the lecture :)

      Index 0 describes $&,

      Thanks for the clarification - I read that in the docs but I didn't see it right.