Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: While loop double counting

by Laurent_R (Canon)
on Nov 23, 2013 at 11:17 UTC ( [id://1064025]=note: print w/replies, xml ) Need Help??


in reply to While loop double counting

You would need to declare $count with the my operator within the getISCount subroutine but before entering the loops.

Also reading again all your files to get the total count can be very inefficient if your files are large, whereas you only need to accumulate the individual line counts. Perhaps something like this, which stores the file names and file line counts in a hash for further use:

use strict; use warnings; use Data::Dumper; my $total_count; my %files = map {$_, 0} glob "./s*.pl"; for my $key (keys %files) { my $count = getcount($key); $files{$key} = $count; $total_count += $count; } sub getcount { local @ARGV = @_; while (<>) {}; return $.; } print Dumper \%files; print "Total size = $total_count lines.\n";
which prints:
$ perl line_count.pl $VAR1 = { './sum.pl' => '19', './summary.pl' => '16', './strict.pl' => '15', './schwartz2.pl' => '13', './sort_hash.pl' => '12', './separat.pl' => '28', './subdiscard3.pl' => '12', './schwartz.pl' => '27', './subdiscard2.pl' => '54', './scope.pl' => '16', './serv.pl' => '28', './shuffle.pl' => '21', './subdiscard.pl' => '23' }; total size = 284 lines.
If you only need to print the counts and don't need to store the values for further use, this can be simplified as follows:
use strict; use warnings; my $total_count; my @files = glob "./s*.pl"; for my $file (@files) { my $count = getcount($file); print "$file \t $count \n"; $total_count += $count; } sub getcount { local @ARGV = @_; while (<>) {}; return $.; } print "Total size = $total_count lines.\n";
which prints this:
$ perl line_count.pl ./schwartz.pl 27 ./schwartz2.pl 13 ./scope.pl 16 ./separat.pl 28 ./serv.pl 28 ./shuffle.pl 21 ./summary.pl 16 ./sort_hash.pl 12 ./strict.pl 15 ./subdiscard.pl 23 ./subdiscard2.pl 54 ./subdiscard3.pl 12 ./sum.pl 19 Total size = 284 lines.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1064025]
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: (7)
As of 2024-04-24 11:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found