Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Too Much Perl?

by TedYoung (Deacon)
on Apr 27, 2006 at 14:10 UTC ( [id://546027]=note: print w/replies, xml ) Need Help??


in reply to Too Much Perl?

If you look at the following code and immediately understand it, then you have been spending way too much time with Perl. I suggest you take a few doses of Java. :-)

perl -p -e '$\+=$_}{'

The -p switch instructs perl to wrap your code with:

LINE: while (defined($_ = <ARGV>)) { # Your code here } continue { die "-p destination: $!\n" unless print $_; }

This transformation is so direct that you can use the token }{ to your advantage. My original code now becomes:

LINE: while (defined($_ = <ARGV>)) { $\ += $_; } { } continue { die "-p destination: $!\n" unless print $_; }

The while loop now focuses on summing the input (converting each line to a number in Perl's fashion, i.e. stopping after any non-number chars). The continue is now attached to an empty run-once block. So, the printing of $_ only occurs once, and after the input has been exhausted, and $_ is now undef. The print statement prints the empty $_, but also always prints $\ (the line terminator), which currently has our sum.

So, this is a sum command. Can be used with wc ... | perl ... or du ... |, etc.

I never code like this in production code, of course! ;-)

Ted Young

($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)

Replies are listed 'Best First'.
Re^2: Too Much Perl?
by apotheon (Deacon) on Apr 27, 2006 at 20:42 UTC

    I guess I'm in the clear, then. I understood what the code did before reading your explanation, but not "immediately", so I should be safe to spend more time with Perl. Whew. What a relief.

    It was the numerical context that hung me up for a few seconds. I kept wondering what good a += operator was to $\ since, like a good little code monkey, I would (almost) never want to add numbers to it from a file for no purpose other than printing them out, and would thus not have fed it numerical input, which didn't make sense to me. Silly me, I was thinking "useful code", not "mild obfu".

    print substr("Just another Perl hacker", 0, -2);
    - apotheon
    CopyWrite Chad Perrin

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-16 11:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found