in reply to $1 doesn't reset?

perlre tells us to use the \G anchor :

while ($res->content =~ m/\G.*?foo(.*?)bar/g) { print "$_ - $1\n"; };

Maybe you'll want to read Death to Dot Star! before you use .*?, but unless we know more about the data, .*? will have to do ;-)

Update: If I run this program :

#!/usr/bin/perl -w use strict; my $string = "fooAbar" . "fooBbar" . "gooCbar" . "fooDfooEbar" . "foo"; while ($string =~ m/\G.*?foo(.*?)bar/g) { print $1, "\n"; };

I get the following, expected output :

H:\>perl -w test.pl A B DfooE

I guess the error lies somewhere else in your regular expression then - maybe post the whole RE together with some sample data.

Replies are listed 'Best First'.
Re: Re: $1 doesn't reset?
by alfie (Pilgrim) on Mar 20, 2001 at 15:54 UTC
    Yes, thanks for the \G info - but somehow it still works if I use $_ within the for loop.

    Also, this now doesn't match anything at all, strangely. Not within while or within a for loop. Only thing I got working is like said within for with $_ as the match.

    Btw., thanks for the link to Death to Dot Star, the .*? is save in this place.

    Sorry that I didn't mention it before, maybe it's important:
    This is perl, v5.6.0 built for i386-linux
    --
    Alfie

      alfie, my understanding is this (and I'm relying on more knowledgable monks to correct me if I'm misunderstanding):

      Working with $_, not $1, is the correct behaviour in the for loop. Because:
      - the regexp match produces a list
      - the for(each) loop cycles through each element of the list, assigning them to $_ as it goes.

      So... $1 doesn't contain each match in turn, because the regexp is only executed once, and the matches are put into $1 to $n, and into a list, and the loop goes round the list, aliasing $_ to each element in turn.

      If you want to use $1, then Corion's suggestion of \G should do the biz. But it looks to me as though the for loop and $_ would be more efficient.

      andy.