develooper Front page | perl.perl5.porters | Postings from October 2014

[perl #122829] Flipflop under recursion

Thread Previous
From:
Father Chrysostomos via RT
Date:
October 28, 2014 04:49
Subject:
[perl #122829] Flipflop under recursion
Message ID:
rt-4.0.18-7046-1414471752-314.122829-15-0@perl.org
On Mon Sep 22 18:13:16 2014, sprout wrote:
> perlop.pod states:
> 
> Each ".." operator
> maintains its own boolean state, even across calls to a subroutine
> that contains it.
> 
> While that is true and well-known, what few know is that recursive
> calls to the containing subroutine do not share that boolean state
> with the outer call.  What’s weirder is that each recursion level
> maintains its own state.  So, for instance, if you have a function
> calling itself recursively to the fifth level, the flip-flop operator
> evaluated at that level will not use the same state again until that
> function is called to that level again.
> 
> I haven’t come up with an example of this weird behaviour yet, but
> I’ll try to post something in the next day or two.

s/day/month/ :-)

# This routine maintains multiple flip-flop states, each with its own
# numeric ID, starting from 1.  Pass the ID as the argument.
sub f {
   my $depth = shift() - 1;
   return f($depth) if $depth;
   return /3/../5/;
}

for(1..20) {
   if (f(1)) {
      my $outer = $_;
      for(1..10){
         print "$outer $_\n" if f(2);
      }
   }
}

The output is:

3 3
3 4
3 5
4 3
4 4
4 5
5 3
5 4
5 5
13 3
13 4
13 5
14 3
14 4
14 5
15 3
15 4
15 5

Now how much code is depending on that bug?  None, I would imagine.  And if someone wanted to write something like the above, an array of closures would be a more straightforward way to do it.  After all, the higher the ID, the slower the flip-flop function.

-- 

Father Chrysostomos


---
via perlbug:  queue: perl5 status: open
https://rt.perl.org/Ticket/Display.html?id=122829

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About