Debian Codegraph @

numsum

raw ◀ ▶
Source reconstructed at patch state 0 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 += $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]+$/);
137 $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 # This function is used so that we can genericize what filehandle
197 # we are getting our information from.
198 sub process_filehandle {
199 my $filehandle = shift;
200 my $number_array_ref = shift;
201
202 while (<$filehandle>) {
203 my $line = $_;
204 chomp($line);
205 if ($opts{'c'} || $opts{'r'}) { # Process columns or rows
206
207 # Make each line column friendly by changing all non-numeric words into 0.
208
209
210 # Some ideas from the #perl channel on irc.freenode.org. Thanks to v, dkr, Khisanth and dudeman
211
212 #$input = join ' ', map { /\D/ ? 0 : $_ } split / +/, $input;
213 #s!(\S+)!$1=~/\D/?0:$1!ge;
214
215 # This one works best.
216 $line =~ s!(\S+)!$1=~/\D/?0:$1!ge;
217
218 push(@$number_array_ref, $line);
219
220 } else { # Normal processing.
221 if ($line =~ /^\s*(\-?[0-9]*\.?[0-9]+)/) {
222 print STDERR "number: $1\n" if ($verbose >= 3);
223 push(@$number_array_ref, $1);
224 }
225 }
226 }
227 return 1;
228 }
229
230
231 # Function for adding up numbers
232 sub add_array {
233 my $arrayref = shift;
234 my $runningtotal = 0;
235 my $number;
236
237 foreach $number (@$arrayref) {
238 print STDERR "$number\n" if ($verbose >= 2);
239 $runningtotal += $number;
240 }
241 return $runningtotal;
242 }
243
244 # Function for summing up the columns.
245 sub sum_columns {
246 my $sum_array_ref = shift;
247 my $input_array_ref = shift;
248
249
250 my $input_array_length = @$input_array_ref;
251 my $x;
252 for ($x = 0; $x < $input_array_length; $x++) {
253 if (${$sum_array_ref}[$x]) {
254 ${$sum_array_ref}[$x] += ${$input_array_ref}[$x];
255 } else {
256 ${$sum_array_ref}[$x] = ${$input_array_ref}[$x];
257 }
258 }
259 return 1;
260 }
261
262 # Lay down some of that perl pod action.
263 =pod
264
265 =head1 NAME
266
267 numsum - numsum program file
268
269 =head1 SYNOPSIS
270
271 B<numsum> [-iIcdhrsvxy] <FILE>
272
273 | B<numsum> [-iIcdhrsvxy] (Input on STDIN from pipeline.)
274
275 B<numsum> [-iIcdhrsvxy] (Input on STDIN. Use Ctrl-D to stop.)
276
277
278 =head1 DESCRIPTION
279
280 B<numsum> is a program that is part of the numeric utilities package. B<numsum>
281 will take all the numbers on stdin and return the sum of those numbers. Currently
282 it only processes the first number on each line. Besides positive numbers, it also
283 handles negative numbers and numbers with decimals.
284
285 =head1 OPTIONS
286
287 -i Only return the integer portion of the final sum.
288 -I Only return the decimal portion of the final sum.
289
290 -c Print out the sum of each column.
291 -r Print out the sum of each row.
292
293 -x <n> Specify a comma seperated list of columns to print.
294 -y <n> Specify a comma seperated list of rows to print.
295
296 -s <string> Specify a string to use as a seperator for columns.
297 This defaults to be consecutive whitespace (\s+).
298
299 -h Help: You're looking at it.
300 -V Increase verbosity.
301 -d Debug mode. For developers
302 -q Quiet mode, don't print any warnings.
303
304 =head1 EXAMPLES
305
306 Simply add up the numbers in a file.
307 $ numsum numbers.txt
308 4315
309
310 Enter your own numbers on STDIN. The last number is the answer.
311 $ numsum
312 4
313 21
314 98
315 100
316 223
317
318 Use it in a command pipeline.
319 $ ls -1s | grep .mp3 | numsum -c -x 5
320 72288
321
322 Add up the total byte count in a http log file.
323 $ cat access_log | awk {'print $10'} numsum
324
325 or
326
327 numsum -c -x 10 access_log
328
329 Add up the columns of numbers of a file.
330
331 $ cat columns
332 1 6 11 16 21
333 2 7 12 17 22
334 3 8 13 18 23
335 4 9 14 19 24
336 5 10 15 20 25
337 $ numsum -c columns
338 15 40 65 90 115
339
340 Add up the 1st, 2nd and 5th columns only.
341
342 $ numsum -c -x 1,2,5 columns
343 15 40 115
344
345 Add up the rows of numbers of a file.
346
347 $ numsum -r columns
348 55
349 60
350 65
351 70
352 75
353
354 Add up the 2nd and 4th rows.
355
356 $ numsum -r -y 2,4 columns
357 60
358 70
359
360 =head1 SEE ALSO
361
362 average(1), bound(1), interval(1), normalize(1), numgrep(1), numprocess(1), random(1), range(1), round(1)
363
364 =head1 COPYRIGHT
365
366 numsum is part of the num-utils package, which is copyrighted by
367 Suso Banderas and released under the GPL license. Please read
368 the COPYING and LICENSE files that came with the num-utils package
369
370 Developers can read the GOALS file and contact me about providing
371 submitions or help for the project.
372
373 =head1 MORE INFO
374
375 More info on numsum can be found at:
376
377 =over 1
378
379 =item B<http://suso.suso.org/programs/num-utils/>
380
381 =back
382
383 =cut
384