Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

\ as a binary operator

by dk (Chaplain)
on Jul 01, 2009 at 12:15 UTC ( [id://776406]=obfuscated: print w/replies, xml ) Need Help??

I'd like to a share a small snippet of code I've recently used not realizing that it's actually a small code pattern on its own. I needed to parse strings in form "a b c d" where these a b c d are arbitrary commands, and each may or may not contain spaces depending on the command. F.ex. phrases "new item x" and "set password a b wwd dc" both contain three words, so simple split wouldn't do. So to parse them correctly, I cut off the first word, analyze it, cut off the next one etc. The part that cuts it off is actually what all this is about. Function "head" that cuts off the first word is very simple:
sub head($) { my ($x, $xs) = split( ' ', ${$_[0]}, 2); ${$_[0]} = $xs; return $x; }
however its use is interesting, because with a special formatting one may get an impression that \ is a binary operator. Here:
my $msg = "new item x"; my $cmd = head \ $msg; if ( $cmd eq 'new') { if ( head \ $msg eq 'item') { ... } } elsif ( $cmd eq 'set') { ... }
where head \ $msg indeed looks like a binary operation :)

Replies are listed 'Best First'.
Re: \ as a binary operator
by jwkrahn (Abbot) on Jul 01, 2009 at 17:03 UTC

    You do realise that $_[0] is an alias to the item passed to the subroutine so you don't need to pass a reference to do the same thing:

    $ perl -le' sub head($) { my ($x, $xs) = split( " ", ${$_[0]}, 2); ${$_[0]} = $xs; return $x; } my $msg = "new item x"; my $cmd = head \ $msg; print for $cmd, $msg; ' new item x $ perl -le' sub head { my ($x, $xs) = split( " ", $_[0], 2); $_[0] = $xs; return $x; } my $msg = "new item x"; my $cmd = head $msg; print for $cmd, $msg; ' new item x
      You're right. Not only that $_[0] is an alias, and the original implementation is redundant because of it, but also that it could be implemented much more concisely, f.ex. sub head($) { $_[0] =~ s/^(\S+)\s+// and $1 }

      However, with these changes, the very point of the post would be missed. There was a reason that I put it in "obfuscation" - because "head $msg" is trivial and "head \ $msg" is fun :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: obfuscated [id://776406]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-23 12:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found