CSVUtils/csv_avg.pm

filter: Statementstmt 100% 38 / 38 Branchbran 100% 4 / 4 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 100% 50 / 50 CC 5 SCAR 6.9
CC
5
Cov
100%
__ANON__
3.0
__ANON__
3.0
BEGIN
1.0
CRAP 2.0
« CSVUtils/csv_shuf_fields.pm ↑ Summary CSVUtils/csv_grep.pm »
1 package App::CSVUtils::csv_avg;
2  
3 2 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
8 2 our $DATE = '2026-07-09'; # DATE
9 2 our $DIST = 'App-CSVUtils'; # DIST
10 2 our $VERSION = '1.038'; # VERSION
11  
12 2 ▶use App::CSVUtils qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
13 gen_csv_util
14 2 );
15  
16 gen_csv_util(
17 name => 'csv_avg',
18 summary => 'Output a summary row which are arithmetic averages of data rows',
19 description => <<'MARKDOWN',
20  
21 Non-numbers will be assumed to be 0.
22  
23 Example:
24  
25 # students.csv
26 name,age
27 andi,13
28 budi,12
29 chandra,12
30 dudi,12
31  
32 % csv-avg students.csv
33 name,age
34 0,12.25
35  
36 % csv-avg students.csv --with-data-row
37 name,age
38 andi,13
39 budi,12
40 chandra,12
41 dudi,12
42 0,12.25
43  
44 MARKDOWN
45 add_args => {
46 %App::CSVUtils::argspecopt_with_data_rows,
47 },
48 tags => ['adds-row','category:summarizing'],
49  
50 3 ▶ on_input_header_row => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
51 3 my $r = shift;
52  
53 # we add this key to the stash
54 3 $r->{summary_row} = [map {0} @{$r->{input_fields}}];
55 3 $r->{row_count} = 0;
56  
57 # because input_* will be cleared by the time of after_read_input,
58 # we save and set it now
59 3 $r->{output_fields} = $r->{input_fields};
60 },
61  
62 4 ▶ on_input_data_row => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
63 4 my $r = shift;
64  
65 4 for my $j (0 .. $#{ $r->{input_fields} }) {
66 2 ▶ no warnings 'numeric', 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
67 12 $r->{summary_row}[$j] += $r->{input_row}[$j]+0;
68 }
69 4 ▶ $r->{code_print_row}->($r->{input_row}) if $r->{util_args}{with_data_rows};
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"util_args"}{"with_data_rows"} 2 2 4
70 4 $r->{row_count}++;
71 },
72  
73 3 ▶ after_read_input => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
74 3 my $r = shift;
75  
76 3 ▶ if ($r->{row_count} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"row_count"} > 0) 2 1 3
77 2 for my $j (0 .. $#{ $r->{output_fields} }) {
78 6 $r->{summary_row}[$j] /= $r->{row_count};
79 }
80 }
81 3 $r->{code_print_row}->($r->{summary_row});
82 },
83 2 );
84  
85 2 1;
86 # ABSTRACT: Output a summary row which are arithmetic averages of data rows
87  
88 __END__
« CSVUtils/csv_shuf_fields.pm ↑ Summary CSVUtils/csv_grep.pm »