Debian Codegraph @

numsum

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