Front page | perl.perl5.porters |
Postings from May 2008
Empty pattern and /o
Thread Next
From:
Bram
Date:
May 16, 2008 14:04
Subject:
Empty pattern and /o
Message ID:
20080516230322.v93gs1rj6okg8goo@horde.wizbit.be
While looking at an old bug report I was, at first, confused by the
following code:
#!/usr/bin/perl -l
use strict;
use warnings;
for (0, 1) {
my $re = ($_ == 0 ? "" : "bar");
my $x = "foo";
$x =~ m/o/o;
if ($x =~ /$re/) {
print "$x =~ /$re/";
}
}
__END__
The output of this:
f o =~ //
f o =~ /bar/
The reason for this is:
$re is empty the first time the loops run so the last succesfull
pattern gets used.
That is m/o/o.
The /o modifier is not dropped so for the next iteration the loop
still matches $x against m/o/ (because of the /o-modifier).
Currently in perlop:
If the PATTERN evaluates to the empty string, the last successfully
matched regular expression is used instead. In this case, only the g
and c flags on the empty pattern is honoured - the other flags are
taken from the original pattern. If no match has previously succeeded,
this will (silently) act instead as a genuine empty pattern (which
will always match).
Should the docs be clearer about the empty pattern and the copying of
the /o modifier? (which can be really confusing...)
Also,
Add: use re 'eval' to the code:
#!/usr/bin/perl -l
use strict;
use warnings;
use re 'eval';
for (0, 1) {
my $re = ($_ == 0 ? "" : "bar");
my $x = "foo";
$x =~ m/o/o;
if ($x =~ /$re/) {
print "$x =~ /$re/";
}
}
__END__
Output:
foo =~ //
So how exactly does use re 'eval' influences the regex?
Kind regards,
Bram
Thread Next
-
Empty pattern and /o
by Bram