Thoughts on Perl and Emacs, technology and writing

The Perl Flip Flop Operator

Mike Taylor dismisses Perl with a pithy reference to a section of its excellent documentation1. For some reason, I mis-remembered that he was complaining about the flip-flop operator rather than context in general.

In scalar context, “..” returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors. Each “..” operator maintains its own boolean state. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again.

Scanning Logfiles

So, say your logfile looks something like this:

... 100,000 lines ...
10:22:25.279 The first interesting line
... 30 more interesting lines ...
10:22:25.772 Another interesting line
10:22:25.772 The last interesting line
10:22:25.779 And then this line isn't interesting any more
... 100,000 lines ...

If you specify the beginning timestamp and end timestamp then you will get one uninteresting line which you can strip with head -n-1.

In a regex I often use an unescaped period (.) to match a period if it doesn’t matter like here

And for anyone thinking useless use of cat… it’s deliberate.

1. With impressive inconsistency, he later on says that Perl is a contender to be His Favourite Language which is why the alternative title for this post was Why Mike Taylor is not my Favourite Blogger.

You can get rid of the head -n-1 stuff by checking the return value of the flip-flop. The return value is a number representing the count, and when the ending condition is met (i.e. the flip-flop is transitioning from true to false) then this number is returned with a trailing E0 such that it’s still numeric but can be distinguished, that is “5E0″ is still parsed as the number 5 but it’s different than “5”, so:

@Evan – I don’t find the behaviour surprising – rather than having global state, I’d say it’s acting like a closure, or an object. If it didn’t behave like this when called multiple times I’d be more surprised.