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

I would like to grab $1 for either regex match but it seems as though if it fails the first match the second gets dropped. Here is my test code:
while(<DATA>) { chomp; if (/string=\"(\d+)\"|static-address\/(.*?)\"/) { print "ONE: $1\n"; } } __DATA__ static string="123456" containing numbers html value <a href="static-address/foo">text</a>
I would expect the output to be:
ONE: 123456 ONE: foo

I'm missing something...

Replies are listed 'Best First'.
Re: help with regex
by moritz (Cardinal) on Mar 27, 2009 at 13:11 UTC
    The captures $1, $2, etc are number by their appearance in the pattern:
    string=\"(\d+)\"|static-address\/(.*?)\" ^^^^^ ^^^^^ $1 $2
      So in other words I will need to check to see if $1 gets set otherwise use $2 correct? I was hoping I could set both to $1
        I guess I could do this:
        while(<DATA>) { chomp; if (/string=\"(\d+)\"|static-address\/(.*?)\"/) { my $id = $1 ? $1 : $2; print "ONE: $id\n"; } } __DATA__ static string="123456" containing numbers html value <a href="static-address/foo">text</a>
Re: help with regex
by jwkrahn (Abbot) on Mar 27, 2009 at 15:59 UTC

    Change:

    print "ONE: $1\n";

    To:

    print "ONE: $+\n";

    To get the output you want.

Re: help with regex
by JavaFan (Canon) on Mar 27, 2009 at 16:25 UTC
    Update your Perl, and write it as:
    if (m{(?|string="(\d+)"|static-address/(.*?)")})