ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I think I'm close to my answer but I can't yet seem to find it. Anyhow, I have a file:
Code:
john 10
mary 20
jack 30
And I'm trying to add up the 2nd column. So, the answer should be 60. Below is my perl code:
Code:
#!/usr/bin/perl
open(FILE, "/tmp/file") or die "Argh!";
while (my $rec=<FILE>){
chomp($rec);
my($name,$num)=split(/ / , $rec);
$num+=$num;
}
print "$num";
I've tried so many ways but now I'm exhausted. Can anyone see what I'm doing wrong? If I put a print "$num"; inside the while loop, it's adding the same number twice. Hmph. Thanks again!
#!/usr/bin/perl -ws
sub usage()
{
print <<"EOF";
# tots up all numbers in a tabular file
# assumes first column is the number to
# be totalled unless specified with -col=n
#
# e.g. try: 'du -s * | total'
#
# or
#
# ls -l | total -col=5
EOF
die "\n";
}
$h ||= undef;
usage if $h;
$col ||=1;
$col--;
while (<>) {
chomp;
next unless /./; # skip blanks
$number = (split)[$col];
$total += $number;
print;
print " ($number)\n";
}
It will display the number on each iteration by 2x. What I needed was to add another variable that held the number - $total+=$num;. That solved my problem.
However, I have one more question . My file is:
Code:
john 10
mary 20
rick -
jack 30
My perl code is:
Code:
#!/usr/bin/perl -w
use strict;
use warnings;
my $total=0;
my $num=0;
open(FILE, "/tmp/file") or die "BlAH!";
while (my $rec=<FILE>){
chomp($rec);
my($name,$num)=split(/ / , $rec);
if ($num =~ /^\d+/){
$total+=$num;
}
}
print "$total\n";
The code prints out the correct sum. However, it gives me this warning:
Quote:
Use of uninitialized value in pattern match (m//) at ./test line 12, <FILE> line 6.
What gives? I already declared variable $num in the beginning. Thanks for guiding me in the right direction guys.
Note that the initialization "my $num = 0" won't be visible from within the while loop because of "my ( $name, $num)". This will create a new local variable named $num.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.