Is Perl's flip-flop operator bugged? It has global state, how can I reset it?

前端 未结 6 1247
旧时难觅i
旧时难觅i 2020-12-13 18:36

I\'m dismayed. OK, so this was probably the most fun Perl bug I\'ve ever found. Even today I\'m learning new stuff about Perl. Essentially,

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 19:18

    The trick is not use the same flip-flop so you have no state to worry about. Just make a generator function to give you a new subroutine with a new flip-flop that you only use once:

    sub make_search {
        my( $left, $right ) = @_;
        sub {
            grep { !( /\Q$left\E/ .. /\Q$right\E/ ) } @{$_[0]};
            }
    }
    
    my $search_sub1 = make_search( 'start', 'never_existed' );
    my $search_sub2 = make_search( 'start', 'never_existed' );
    
    
    my @foo = qw/foo bar start baz end quz quz/;
    
    my $count1 = $search_sub1->( \@foo );
    my $count2 = $search_sub2->( \@foo );
    
    print "count1 $count1 and count2 $count2\n";
    

    I also write about this in Make exclusive flip-flop operators.

提交回复
热议问题