Google Answers Logo
View Question
 
Q: Perl One liners ( No Answer,   3 Comments )
Question  
Subject: Perl One liners
Category: Computers > Programming
Asked by: nemrod-ga
List Price: $3.00
Posted: 16 Sep 2005 19:02 PDT
Expires: 16 Oct 2005 19:02 PDT
Question ID: 568957
I have a list of integers in column in a text file.

2 34 787 0 5
3 0 123 4 22
...

I need to sum up all F[3] and print the total.
How can you do that with a perl one liner?
Answer  
There is no answer at this time.

Comments  
Subject: Re: Perl One liners
From: bozo99-ga on 17 Sep 2005 05:59 PDT
 
Remebering that the columns are numbered from 0, here you go.

$ cat IN
2 34 787 0 5
3 0 123 4 22
$ perl -e 'while (<>) {@_=split(/\s+/); $sum+=$_[3]} print "$sum\n"' < IN
4
Subject: Re: Perl One liners
From: uncle_ziba-ga on 17 Sep 2005 07:05 PDT
 
while bozo's solution works it can be more elegant. Why not use the
implicit loop and autosplit? like this:

perl -alne '$sum+=$F[3]; END {print $sum}' IN
Subject: Re: Perl One liners
From: nemrod-ga on 21 Sep 2005 09:52 PDT
 
Excellen solutions, thank you very much.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy