Stupid regex problem...

L

Leif K-Brooks

I have the following Perl code. When I run it, Perl complains that $1 is
undefined. If I change (foo)|(bar) to (bar)|(foo), it works fine. I know
I could just use /(foo|bar)/, but this is just a simplified example.

use strict;
use warnings;

my $text = 'bar';
if ($text =~ /(?:(foo)|(bar))/) {
print $1;
}
 
T

Tassilo v. Parseval

Also sprach Leif K-Brooks:
I have the following Perl code. When I run it, Perl complains that $1 is
undefined. If I change (foo)|(bar) to (bar)|(foo), it works fine. I know
I could just use /(foo|bar)/, but this is just a simplified example.

use strict;
use warnings;

my $text = 'bar';
if ($text =~ /(?:(foo)|(bar))/) {
print $1;
}

You have two capturing pairs of parens of which only one will (or none
actually) can match. There is the special variable $+ (see perlvar.pod)
which holds the actual match:

my $text = 'bar';
if ($text =~ /(?:(foo)|(bar))/) {
print $+;
}
__END__
bar

Tassilo
 
A

Andreas Kahari

I have the following Perl code. When I run it, Perl complains that $1 is
undefined. If I change (foo)|(bar) to (bar)|(foo), it works fine. I know
I could just use /(foo|bar)/, but this is just a simplified example.

use strict;
use warnings;

my $text = 'bar';
if ($text =~ /(?:(foo)|(bar))/) {
print $1;
}

You never actually posed a question, so I will assume that you
meant "Why does is $1 undefined?".

Well, the regex as a whole matches, and the part that matched
the first parenthesis is stored in $1 and the part that matches
the second parentesis is stored in $2. Clearly, nothing matches
the first parenthesis, so $1 will be undefined.
 
L

Leif K-Brooks

Tassilo v. Parseval wrote:

You have two capturing pairs of parens of which only one will (or none
actually) can match.

Ok, that makes sense. I was assuming the parens would only store if they
were the ones used in the alternation. Is there any way to make that happen?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top