develooper Front page | perl.perl5.porters | Postings from July 2001

Re: [ID 20010724.007] REGEXP bug in perl 5.6.1

Thread Previous
Jeff 'japhy/Marillion' Pinyan
July 24, 2001 21:08
Re: [ID 20010724.007] REGEXP bug in perl 5.6.1
Message ID:
On Jul 24, stuart lory said:

>The situation occurs when using /o in a regexp.
>Specifically I am using /mos, and the bug does not
>show up if I change the regexp to /ms. My
>understanding is /o means 'compile pattern once'. But
>since I am doing this in a subroutine, I was expecting
>the regexp to go out of scope when the subroutine
>What happens in test #2 is almost certainly a bug
>since I am passing in two different strings and the
>second string is being modified in a place where the
>first string had been changed. I think it's probably
>easier just to show an example output:

Long story short:

The /o modifier is SUPREME.  If you write:

  sub foo {
    $x =~ /$y/o;

then the first time foo() is called, the regex is compiled.  Never again
will it be compiled.  Thus, this behavior is not buggy.

In your case, your regex is compiled as


all the time.  However, the RIGHT-HAND SIDE of your regex is not bound by
the /o rule, and thus, you get the behavior:

  for ( [ brown => 'purple' ], [ over => 'into' ] ) {
    my ($find, $replace) = @$_;
    $X =~ s/$find/$replace/o;

First, $X gets "brown" replaced with "purple".  Next, it TRIES to replace
"brown" with "into", but fails, since there's no more brown to be
found.  It uses "brown" because the regex will ONLY BE COMPILED ONCE.

Let's examine your second case:

  for ( [ \$Y, brown => 'purple' ], [ \$Z, over => 'into' ] ) {
    my ($str, $find, $replace) = @$_;
    $$str =~ s/$find/$replace/o;

On the first iteration, $Y is changed -- "brown" becomes "purple".  On the
second iteration, $Z is changed -- "brown" becomes "into".  Why?  Because
the regex (/$find/) was ONLY compiled ONCE.

Does this clarify the behavior?

Jeff "japhy" Pinyan
I am Marillion, the wielder of Ringril, known as Hesinaur, the Winter-Sun.
Are you a Monk?
Perl Programmer at RiskMetrics Group, Inc.
Acacia Fraternity, Rensselaer Chapter.         Brother #734
**      Manning Publications, Co, is publishing my Perl Regex book      **

Thread Previous Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About