in reply to Re^2: 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.

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__

Replies are listed 'Best First'.
Re^4: Multiple uses of (?{ code }) do not appear to be called
by bsdz (Friar) on Dec 29, 2006 at 14:50 UTC
    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?

        The "local our" bit felt contradictory.. though that doesn't mean it doesn't make sense.
Re^4: Multiple uses of (?{ code }) do not appear to be called
by rhesa (Vicar) on Dec 29, 2006 at 15:42 UTC
    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.

        Right, gotcha. I was confused, since the perldocs say: "An "our" declares the listed variables to be valid globals within the enclosing block". It didn't occur to me at first that an inner scope would simply reuse an "our" in the enclosing scope. I now also see what diotalevi meant with stomping on my parent :)

      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
        See, this is why ourperl is so confusing :-)

        You are bitten by the magic of $a and $b:

        #!/usr/bin/perl -l use strict; { local our $x = "A" } { our $y = "B" } print "x=$x"; print "y=$y"; __END__ Variable "$x" is not imported at our2.pl line 7. Variable "$y" is not imported at our2.pl line 8. Global symbol "$x" requires explicit package name at our2.pl line 7. Global symbol "$y" requires explicit package name at our2.pl line 8. Execution of our2.pl aborted due to compilation errors.