Debian Codegraph @

numsum

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