in reply to Re^2: Solution for your prof
in thread <> diamond Operator
You're actually getting the totals for all the files. Try the following:
#!/perl/bin/perl # # Author: L.H # Script Name: lab6-1 # Date Written: March 15, 2005 # Purpose: Basic I/0 # # use strict; foreach my $file (@ARGV) { open(FILE, "$file"); my $sum = 0; while (<FILE>) { $sum+=$_; print "$file $_\n"; } print "$sum\n"; close( FILE ); }
The major change is the my $sum = 0; line. It scopes $sum to be within the foreach-loop. This means that it gets reset every time. You'll notice I added strict to my version. This provides some typo-checking, and also requires that you declare your variables (preferably with my) beforehand.
This node was much better than your previous nodes. You posted what you tried and why it didn't work. This means we'll help you out, explaining why what you did didn't work and how to improve it. We'll edit, not create.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Solution for your prof
by kocaweb (Initiate) on Apr 07, 2005 at 21:55 UTC | |
by dragonchild (Archbishop) on Apr 08, 2005 at 01:06 UTC | |
by starbolin (Hermit) on Apr 08, 2005 at 03:31 UTC |