SPUG: double-dot stylin'

Michael R. Wolf MichaelRWolf at att.net
Thu Apr 22 09:17:19 CDT 2004

As a way to illustrate how the double-dot operator (in a scalar
context) operates as a flip-flop, I put this code together. It's a
classic example of parsing an email message -- the header is the first
line through a blank line; the body is the rest.

while (<>) {
    if (1 .. /^\s*$/) {
	push @header, $_;
    } else {
	push @body, $_;

Then I started playing golf, taking away unnecessary code, and

Unfortunately this minimal version didn't work

    push 1 .. /^\s*$/ ? @header : @body, $_ while (<>);

So I repeated the 'push' and '$_' (ugh... repeated code -- what would
Fowler say?) and came up with this.

    1 .. /^\s*$/ ? push @header, $_ : push @body, $_ while (<>);

But even with 8 years of Perl under my belt, it's too dense and
cryptic for me to look at.

This at least exposes the "?" in a way that hints at the ternary
operator, but it's not so obvious that the 'while' is a modifier, and
subordinate to the ternary, instead of an empty loop.

    1 .. /^\s*$/           ? 
        push @header, $_   : 
        push @body, $_ 
    while (<>);

I'm sure Tim will suggest getting rid of the 'while' at the end, but
that takes up another whole line and two printable characters....

    while (<>) {
        1 .. /^\s*$/           ? 
            push @header, $_   : 
            push @body, $_

Better formatting ideas?

Michael R. Wolf
    All mammals learn by playing!
        MichaelRWolf at att.net

More information about the spug-list mailing list