What I would wish for is a flip-flop that is tied to it's lexical scope and gets reset when control leaves the scope.

Such a system would not work, since { $_ eq $look_for .. 1 } is an anonymous subroutine, which also has a lexical scope on its own. So with your proposal, the flipflop would be reset after each invocation.

The same problem comes up for the most common use case, which is in oneliners like

perl -ne 'print if /regex1/../regex2/'

where the -n flag creates a while-loop, and thus an implicit lexical scope, around the flipflop.

A better approach (but harder to explain) would be clone the flipflop along with all other closures when the outer scope is entered.

Let me try to explain that with a small example:

use strict; use warnings; use 5.010; sub gen_iter { my $a = shift; sub { $a++ }; } my $it1 = gen_iter 10; my $it2 = gen_iter 20; say $it1->(); say $it2->(); say $it1->(); say $it2->(); __END__ 10 20 11 21

You can see that $it1 and $it2 have different instances of the $a variable. This is implemented by cloning the lexical pad of the inner subroutine as soon as gen_iter is entered.

So I think the most intuitive behavior would be to clone the flipflop state along with the lexical pad when the outer scope is entered.

But I guess that the flipflop operator isn't used often enough to motivate a core hacker to actually implement such a change.


In reply to Re^7: flip-flop flop by moritz
in thread flip-flop flop by morgon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.