Debian Codegraph @

numsum

raw ◀ ▶
5 Debian patches touch this file
1 #!/usr/bin/perl -w
2
3 # numsum: This program adds up all numbers it encounters and prints out
4 # the total at the end on STDOUT.
5 #
6 # Copyright (C) 2002-2004 Suso Banderas
7
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 #
22 # You may contact the author at <[email protected]>.
23
24 #######################
25 # VARIABLES AND SETUP #
26 #######################
27
28 use Getopt::Std;
29 #use strict;
30 use vars qw/ %opts /;
•31 use Scalar::Util qw/looks_like_number/;
•32 +$Getopt::Std::STANDARD_HELP_VERSION = 1;
33
34 my ($file, $finalsum, @number_array, @columns_to_print, @column_output, $output_line, $string_seperator, $verbose);
35
36 getopts('123456789cdhiIqrs:Vx:y:', \%opts);
37
38
39 if ($opts{'h'}) {
40 &help;
41 exit(0);
42 }
43
44 if ($opts{'d'}) {
45 $verbose = 3;
46 print STDERR "Debug mode\n";
47 } elsif ($opts{'V'}) {
48 $verbose = 2;
49 print STDERR "Verbose mode\n";
50 } elsif($opts{'q'}) {
51 $verbose = 0; # No output except the final answer.
52 } else {
53 $verbose = 1; # Normal output.
54 }
55
56 # I'm not sure whether this should stay in or not. It's mainly just for convience.
57 # It's a bad hack because you can only specify 1 through 9. Maybe sometime I'll figure
58 # out how to bypass getopts to specify extra options.
59 for ($n = 1 ; $n < 10; $n++) {
60 if ($opts{$n}) {
61 $opts{'c'} = 1;
62 $opts{'x'} = $n;
63 }
64 }
65
66 if ($opts{'x'}) {
67 @columns_to_print = split(/,/, $opts{'x'});
68 }
69
70 if ($opts{'y'}) {
71 @rows_to_print = split(/,/, $opts{'y'});
72 }
73
74 if ($opts{'s'}) {
75 $string_seperator = $opts{'s'};
76 } else {
77 $string_seperator = "\\s+";
78 }
79
80
81 ################
82 # MAIN PROGRAM #
83 ################
84
85 if (@ARGV) {
86 foreach $file (@ARGV) {
87 print STDERR "Reading from file $file.\n" if ($verbose >= 2);
88 open (ARGFILE, "$file") && process_filehandle(\*ARGFILE, \@number_array)
89 || $verbose && warn "Couldn't open file $file for reading: $!\n";
90 close(ARGFILE);
91 }
92 } else {
93 print STDERR "Reading from STDIN.\n" if ($verbose >= 2);
94 process_filehandle(\*STDIN, \@number_array);
95 }
96
97 my $number_array_length = @number_array;
98
99 if ($opts{'c'}) { # Handle column sum output.
100
101 my @column_output = ();
102 my $i;
103 for ($i = 0; $i < $number_array_length; $i++) {
104 my @add_this_array = split(/$string_seperator/, $number_array[$i]);
105 sum_columns(\@column_output, \@add_this_array);
106 }
107
108 # Now print out the columular output.
109 if ($opts{'x'}) {
110 my @final_output = ();
111 foreach $column_number (@columns_to_print) {
112 push (@final_output, $column_output[$column_number-1]);
113 }
114 $output_line = join(" ", @final_output);
115 } else {
116 $output_line = join(" ", @column_output);
117 }
118
119 print "$output_line\n";
120
121 } elsif ($opts{'r'}) { # Handle row sum output.
122
123 my $i;
124 if ($opts{'y'}) {
125 foreach $row_number (@rows_to_print) {
126 my @add_this_array = split(/ /, $number_array[$row_number-1]);
127 my $row_sum = 0;
128 foreach $row_value (@add_this_array) {
•129 $row_sum = decimals_friendly_sum( $row_sum, $row_value );
130 }
131 print "$row_sum\n";
132 }
133 } else {
134 for ($i = 0; $i < $number_array_length; $i++) {
135 my @add_this_array = split(/ /, $number_array[$i]);
136 my $row_sum = 0;
137 foreach $row_value (@add_this_array) {
•138 next if ($row_value !~ m/^\-?[0-9]*\.?[0-9]+$/);
139 $row_sum = decimals_friendly_sum( $row_sum, $row_value );
140 }
141 print "$row_sum\n";
142 }
143 }
144
145 } else {
146 $finalsum = add_array(\@number_array);
147
148 if ($opts{'i'}) {
149 $finalsum = int($finalsum);
150 } elsif ($opts{'I'}) {
151 if ($finalsum == int($finalsum)) {
152 $finalsum = 0;
153 } else {
154 $finalsum =~ s/^(\-?)[0-9]*\.([0-9]*)$/$1.$2/;
155 }
156 }
157
158 print "$finalsum\n";
159 }
160
161 exit(0);
162
163
164 ###############
165 # SUBROUTINES #
166 ###############
167
168 sub help {
169 print <<"EOF";
170 ---------------------------------------------------------------------------
171 numsum : A program that adds up all numbers of input and returns the sum.
172 ---------------------------------------------------------------------------
173 Usage:
174 numsum [options] <file> (Input from a file.)
175 | numsum [options] (Input from command pipeline.)
176 numsum [options] (Input on STDIN. Use Ctrl-D to stop.)
177
178 Options:
179 -i Only return the integer portion of the final sum.
180 -I Only return the decimal portion of the final sum
181
182 -c Print out the sum of each column.
183 -r Print out the sum of each row.
184
•185 -x <n> Specify a comma separated list of columns to print.
186 -y <n> Specify a comma separated list of rows to print.
187
•188 -s <string> Specify a separator string for spliting columns.
189 This defaults to consecutive whitespace.
190
191 -d Debug. For developers only.
192 -h Help: You're looking at it.
193 -V Increase verbosity.
194 -q Quiet mode, don't print any warnings.
195 EOF
196 }
197
•198 sub HELP_MESSAGE{
199 &help();
200 }
201
202 sub decimals_friendly_sum
203 {
204 # try summing 1.99 and -1.90 to understand why
205 my $number_a = shift;
206 my $number_b = shift;
•207 return $number_a if( ! looks_like_number( $number_b ) );
208 my $dec_a = ( $number_a =~ /\.([^\.]*)$/ ? length($1) : 0 );
209 my $dec_b = ( $number_b =~ /\.([^\.]*)$/ ? length($1) : 0 );
210 my $factor = 10 ** ( $dec_a > $dec_b ? $dec_a : $dec_b );
211 $number_a *= $factor;
212 $number_b *= $factor;
213 return ( $number_a + $number_b ) / $factor;
214 }
215
216 # This function is used so that we can genericize what filehandle
217 # we are getting our information from.
218 sub process_filehandle {
219 my $filehandle = shift;
220 my $number_array_ref = shift;
221
222 while (<$filehandle>) {
223 my $line = $_;
224 chomp($line);
225 if ($opts{'c'} || $opts{'r'}) { # Process columns or rows
226
227 # Make each line column friendly by changing all non-numeric words into 0.
228
229
230 # Some ideas from the #perl channel on irc.freenode.org. Thanks to v, dkr, Khisanth and dudeman
231
232 #$input = join ' ', map { /\D/ ? 0 : $_ } split / +/, $input;
233 #s!(\S+)!$1=~/\D/?0:$1!ge;
234
235 # This one works best.
•236 #$line =~ s!(\S+)!$1=~/^(\-?[0-9]*\.?[0-9]+)$/?$1:0!ge;
237
238 push(@$number_array_ref, $line);
239
240 } else { # Normal processing.
241 if ($line =~ /^\s*(\-?[0-9]*\.?[0-9]+)/) {
242 print STDERR "number: $1\n" if ($verbose >= 3);
243 push(@$number_array_ref, $1);
244 }
245 }
246 }
247 return 1;
248 }
249
250
251 # Function for adding up numbers
252 sub add_array {
253 my $arrayref = shift;
254 my $runningtotal = 0;
255 my $number;
256
257 foreach $number (@$arrayref) {
258 print STDERR "$number\n" if ($verbose >= 2);
•259 $runningtotal = decimals_friendly_sum( $runningtotal, $number );
260 }
261 return $runningtotal;
262 }
263
264 # Function for summing up the columns.
265 sub sum_columns {
266 my $sum_array_ref = shift;
267 my $input_array_ref = shift;
268
269
270 my $input_array_length = @$input_array_ref;
271 my $x;
272 for ($x = 0; $x < $input_array_length; $x++) {
•273 ${$sum_array_ref}[$x] = 0 if( ! defined( ${$sum_array_ref}[$x] ) );
•274 ${$sum_array_ref}[$x] = decimals_friendly_sum( ${$sum_array_ref}[$x], ${$input_array_ref}[$x] );
275 }
276 return 1;
277 }
278
279 # Lay down some of that perl pod action.
280 =pod
281
282 =head1 NAME
283
284 numsum - numsum program file
285
286 =head1 SYNOPSIS
287
288 B<numsum> [-iIcdhrsvxy] <FILE>
289
290 | B<numsum> [-iIcdhrsvxy] (Input on STDIN from pipeline.)
291
292 B<numsum> [-iIcdhrsvxy] (Input on STDIN. Use Ctrl-D to stop.)
293
294
295 =head1 DESCRIPTION
296
•297 B<numsum>
298 will take all the numbers on stdin and return the sum of those numbers. Currently
•299 it only processes the first number on each line
300 (unless when using the -x option).
301 Besides positive numbers, it also
302 handles negative numbers and numbers with decimals.
303
304 =head1 OPTIONS
305
306 -i Only return the integer portion of the final sum.
307 -I Only return the decimal portion of the final sum.
308
•309 -c Print out the sum of each column.
310 -r Print out the sum of each row.
311
•312 -x <n> Specify a comma separated list of columns to print.
313 -y <n> Specify a comma separated list of rows to print.
314
•315 -s <string> Specify a string to use as a separator for columns.
316 This defaults to be consecutive whitespace (\s+).
317
318 -h Help: You're looking at it.
319 -V Increase verbosity.
320 -d Debug mode. For developers
321 -q Quiet mode, don't print any warnings.
322
323 =head1 EXAMPLES
324
325 Simply add up the numbers in a file.
326 $ numsum numbers.txt
327 4315
328
329 Enter your own numbers on STDIN. The last number is the answer.
330 $ numsum
331 4
332 21
333 98
334 100
335 223
336
337 Use it in a command pipeline.
338 $ ls -1s | grep .mp3 | numsum -c -x 5
339 72288
340
341 Add up the total byte count in a http log file.
342 $ cat access_log | awk {'print $10'} numsum
343
344 or
345
346 numsum -c -x 10 access_log
347
348 Add up the columns of numbers of a file.
349
350 $ cat columns
351 1 6 11 16 21
352 2 7 12 17 22
353 3 8 13 18 23
354 4 9 14 19 24
355 5 10 15 20 25
356 $ numsum -c columns
357 15 40 65 90 115
358
359 Add up the 1st, 2nd and 5th columns only.
360
361 $ numsum -c -x 1,2,5 columns
362 15 40 115
363
364 Add up the rows of numbers of a file.
365
366 $ numsum -r columns
367 55
368 60
369 65
370 70
371 75
372
373 Add up the 2nd and 4th rows.
374
375 $ numsum -r -y 2,4 columns
376 60
377 70
378
379 =head1 SEE ALSO
380
•381 numaverage(1), numbound(1), numinterval(1), numnormalize(1), numgrep(1), numprocess(1), numrandom(1), numrange(1), numround(1)
382
383 =head1 COPYRIGHT
384
385 numsum is part of the num-utils package, which is copyrighted by
386 Suso Banderas and released under the GPL license. Please read
387 the COPYING and LICENSE files that came with the num-utils package
388
389 Developers can read the GOALS file and contact me about providing
390 submitions or help for the project.
391
392 =head1 MORE INFO
393
394 More info on numsum can be found at:
395
396 =over 1
397
•398 =item B<http://suso.suso.org/xulu/Num-utils>
399
400 =back
401
402 =cut
403