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

Hi everyone,

I am having problems with the (?{}) construct within a regex. In the code below, the print statement works fine. However, nothing gets pushed to the array. Does anyone have any insight on what is happening here? The input is on a line of C code. Thanks in advance.

Update: Oh yes, I'm using 5.8.3 ActiveState on Win32.
my @conds; my $outer_conditional = qr/ ( #(??{$term}) (?: (?: && | \|\| | & | \| | \^ ) #(??{$term}) )+ ) (?{push(@conds, $^N), print " cond $^N\n"}) /x; while ($line =~ /$outer_conditional/g) { my $conds = join ", ",@conds; print "Conditionals: $conds\n"; }
--ColonelPanic


When's the last time you used duct tape on a duct? --Larry Wall

Replies are listed 'Best First'.
Re: executing code within a regex
by tilly (Archbishop) on May 07, 2004 at 21:33 UTC
    For the record, if $line is set to "hello && world || other" then the output that I get is:
    cond && Conditionals: && cond || Conditionals: &&, ||
    which I think is what you want. So I'd suggest filing a bug report.

    (This was tested in Perl 5.8.3 under Linux.)

      Thanks a lot for trying it out. I guess I'll have to work around that for now.


      When's the last time you used duct tape on a duct? --Larry Wall
Re: executing code within a regex
by BrowserUk (Patriarch) on May 07, 2004 at 22:18 UTC

    Strange. Using AS809 (5.8.3 for win32), I get the expected results.

    $line = 'this && that || other & these | those'; output: P:\test>test3 cond && Conditionals: && cond || Conditionals: &&, || cond & Conditionals: &&, ||, & cond | Conditionals: &&, ||, &, |

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: executing code within a regex
by hv (Prior) on May 07, 2004 at 23:00 UTC

    It isn't entirely clear what you're seeing compared to what you expect to see, but I can't see a problem with the code you show under 5.8.3 on Linux.

    One thing that might be worth a try is to replace the declaration:

    my @conds;
    with:
    our @conds;
    - depending on precisely how you're using this in the real code, it may be that the regexp-eval is failing to see the right variable.

    Hugo

Re: executing code within a regex
by dave_the_m (Monsignor) on May 07, 2004 at 23:03 UTC
    Note that there are many problems with using lexical variables within (?{...}) contructs with current Perl; in your real program (as opposed to the snippet above), is where @cond is declared and where it is accessed more involved, eg is part of the code actually contained within a function?
      Yes, it turned out that when I ran the code as displayed above, it worked. The problem went away when I moved the @cond variable to a greater scope. Thanks everyone for your help.


      When's the last time you used duct tape on a duct? --Larry Wall