in reply to Re: Multiple uses of (?{ code }) do not appear to be called
in thread Multiple uses of (?{ code }) do not appear to be called

I must admit I am not too hot on closures either but another interesting observation is that making @o global appears to cure the problem.
my @o; foo(); foo(); foo(); sub foo { my $window = "a b X20 c X5 d e X17 X12"; @::o = (); my @m = ($window =~ m/(X\d+(?{push @::o, pos()}))/g); print join(" ", "Matches:", @m, "\n"); print join(" ", "Offsets:", @::o, "\n\n"); }
Could that be explained by closures too? I am still examining the re 'debug' output.

Replies are listed 'Best First'.
Re^3: Multiple uses of (?{ code }) do not appear to be called
by blazar (Canon) on Dec 29, 2006 at 14:05 UTC
    I must admit I am not too hot on closures either but another interesting observation is that making @o global appears to cure the problem.

    Then perhaps instead of @::o = () you may want to use our in conjunction with local:

    #!/usr/bin/perl use strict; use warnings; sub foo { my $window = "a b X20 c X5 d e X17 X12"; local our @o; my @m = $window =~ m/(X\d+(?{push @o, pos}))/g; print "Matches: @m,\n"; print "Offsets: @o,\n\n"; } foo; foo; foo; __END__
      I'll be damned. It feels a little contradictory but it works. Maybe it's time I re-read all that Perl literature again!
        I'll be damned. It feels a little contradictory but it works. Maybe it's time I re-read all that Perl literature again!

        What feels a little contradictory?

      Heh, nifty. But why not simply say our @o = ();? Surely the scope is still limited to the sub. I'm a bit puzzled by how local interacts with our here.

        local our @o;
        is the same as
        our @o;
        local @o;

        our @o; disables use strict for @o.
        local @o; protects the existing value of @o (and initialized @o to an empty array).

        Without the local, there's no scoping. That's bad! If the caller also uses @o, you just clobbered the caller's variable.

        If your function is reentrant then you've just protected your parent against your stomping on it.

        ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        If you don't specify the local modifier then @o is visible outside the scope. I.e.
        use strict; { local our $a = "A"; } { our $b = "B"; } print "a = $a\n"; print "b = $b\n"; __DATA__ a = b = B
Re^3: Multiple uses of (?{ code }) do not appear to be called
by jettero (Monsignor) on Dec 29, 2006 at 13:23 UTC

    Could that be explained by closures too? I am still examining the re 'debug' output.

    The debug output clearly shows you were correct in your first post — that the matching does indeed function. The problem (that is definitely cured by using a global @o) is that your regex code was pushing onto the wrong @o, one nolonger in any scope accessable by non-perl-deities.

    -Paul