http://www.perlmonks.org?node_id=109351

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

I've been working through Japhy's regular expression draft and I'm confused by the operation of the @+ array. Rather than keep bugging Japhy, I thought I'd ask here!

The exercise from Chapter 3 asks for the contents fo the @- and @+ arrays after matching /(\w+)\W+(.*)/ on "where are you".

I would expect the contents to be [0, 0, 6] and [14, 5, 14] respectively, but instead the code

#!/usr/bin/perl -w use strict; "where are you?" =~ /(\w+)\W+(.*)/; print "\$1 is $1, \@- contains $-[0], $-[1], $-[2]\n"; print "\$2 is $2, \@+ contains $+[0], $+[1], $-[2]\n";

gives the result

$1 is where, @- contains 0, 0, 6 $2 is are you?, @+ contains 14, 5, 6

Why does $+[2] contain 6 rather than 14?

Replies are listed 'Best First'.
Re: Regex and @+
by tachyon (Chancellor) on Aug 31, 2001 at 15:50 UTC

    Typo problem. In your second line for @+ you have $-[2] when you meant/expected $+[2] Change that and you get what you expect.

    For those who might be wondering the @+ and @- arrays are the replacements for the much maligned $` $' and $" regex vars in 5.6 But who uses them (outside of sigs that is :-) Have a look at japhy's excellent book (now chapter 5 I think) for a run down.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Oh Nuts! Re: Regex and @+
by claree0 (Hermit) on Aug 31, 2001 at 15:47 UTC
    Typos-R-us! Once I get the code correct, I get the expected results!

      small remark ... you could have had an easier life by writing

      print "\$1 is $1, \@- contains ", join(', ', @-), "\n"; print "\$2 is $2, \@+ contains ", join(', ', @+), "\n";
      There is still the chance of typos, but it's decreased and easier detected.

      -- Hofmator