CSVUtils/csv_add_fields.pm

filter: Statementstmt 97.1% 68 / 70 Branchbran 76.6% 23 / 30 Conditioncond 71.4% 5 / 7 MC/DCmcdc 50.0% 2 / 4 Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 88.9% 105 / 118 CC 22 SCAR 23.6
CC
22
Cov
90%
__ANON__
16.1
__ANON__
5.1
__ANON__
3.8
CRAP 10.6
« CSVUtils/csv_lookup_fields.pm ↑ Summary CSVUtils/csv_trim.pm »
1 package App::CSVUtils::csv_add_fields;
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 compile_eval_code
15 eval_code
16 2 );
17  
18 gen_csv_util(
19 name => 'csv_add_fields',
20 summary => 'Add one or more fields to CSV file',
21 description => <<'MARKDOWN',
22  
23 The new fields by default will be added at the end, unless you specify one of
24 `--after` (to put after a certain field), `--before` (to put before a certain
25 field), or `--at` (to put at specific position, 1 means the first field). The
26 new fields will be clustered together though, you currently cannot set the
27 position of each new field. But you can later reorder fields using
28 <prog:csv-sort-fields>.
29  
30 If supplied, your Perl code (`-e`) will be called for each row (excluding the
31 header row) and should return the value for the new fields (either as a list or
32 as an arrayref). `$_` contains the current row (as arrayref, or if you specify
33 `-H`, as a hashref). `$main::row` is available and contains the current row
34 (always as an arrayref). `$main::rownum` contains the row number (2 means the
35 first data row). `$csv` is the <pm:Text::CSV_XS> object. `$main::fields_idx` is
36 also available for additional information.
37  
38 If `-e` is not supplied, the new fields will be getting the default value of
39 empty string (`''`).
40  
41 MARKDOWN
42 add_args => {
43 %App::CSVUtils::argspec_fields_1plus_nocomp,
44 %App::CSVUtils::argspecopt_eval,
45 %App::CSVUtils::argspecopt_hash,
46 after => {
47 summary => 'Put the new field(s) after specified field',
48 schema => 'str*',
49 completion => \&_complete_field,
50 },
51 before => {
52 summary => 'Put the new field(s) before specified field',
53 schema => 'str*',
54 completion => \&_complete_field,
55 },
56 at => {
57 summary => 'Put the new field(s) at specific position '.
58 '(1 means at the front of all others)',
59 schema => 'posint*',
60 },
61 },
62 add_args_rels => {
63 choose_one => [qw/after before at/],
64 },
65 tags => ['category:munging','adds-fields'],
66  
67 examples => [
68 {
69 summary => 'Add a few new blank fields at the end',
70 argv => ['file.csv', 'field4', 'field6', 'field5'],
71 test => 0,
72 'x.doc.show_result' => 0,
73 },
74 {
75 summary => 'Add a few new blank fields after a certain field',
76 argv => ['file.csv', 'field4', 'field6', 'field5', '--after', 'field2'],
77 test => 0,
78 'x.doc.show_result' => 0,
79 },
80 {
81 summary => 'Add a new field and set its value',
82 argv => ['file.csv', 'after_tax', '-e', '$main::row->[5] * 1.11'],
83 test => 0,
84 'x.doc.show_result' => 0,
85 },
86 {
87 summary => 'Add a couple new fields and set their values',
88 argv => ['file.csv', 'tax_rate', 'after_tax', '-e', '(0.11, $main::row->[5] * 1.11)'],
89 test => 0,
90 'x.doc.show_result' => 0,
91 },
92 ],
93  
94 12 ▶ on_begin => sub {
Subroutine __ANON__: called CC=3 SCAR=13.3
95 12 my $r = shift;
96  
97 # check arguments
98 12 ▶ if (!defined($r->{util_args}{fields}) || !@{ $r->{util_args}{fields} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $r->{"util_args"}{"fields"} && @{$r->{"util_args"}{"fields"};}) 0 12 12
Condition33%1/3
defined $r->{'util_args'}{'fields'} && @{$r->{'util_args'}{'fields'};}
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $r->{'util_args'}{'fields'} && @{$r->{'util_args'}{'fields'};}
defined $r->{'util_args'}{'fields'} @{$r->{'util_args'}{'fields'};}
Truth table33%1/3
A && B
A= defined $r->{'util_args'}{'fields'}B= @{$r->{'util_args'}{'fields'};}
ABresult
0X0
100
111
99 0 die [400, "Please specify one or more fields (-f)"];
100 }
101 },
102  
103 12 ▶ on_input_header_row => sub {
Subroutine __ANON__: called CC=16 SCAR=27.8
104 12 my $r = shift;
105  
106 # check that the new fields are not duplicate (against existing fields
107 # and against itself)
108 12 my %seen;
109 12 for (@{ $r->{util_args}{fields} }) {
110 18 ▶ unless (length $_) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $_) 1 17 18
111 1 die [400, "New field name cannot be empty"];
112 }
113 17 ▶ if (defined $r->{input_fields_idx}{$_}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r->{"input_fields_idx"}{$_}) 1 16 17
114 1 die [412, "Field '$_' already exists"];
115 }
116 16 ▶ if ($seen{$_}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen{$_}++) 1 15 16
117 1 die [412, "Duplicate new field '$_'"];
118 }
119 }
120  
121 # determine the position at which to insert the new fields
122 9 my $new_fields_idx;
123 9 ▶ if (defined $r->{util_args}{at}) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $r->{'util_args'}{'at'}) { } 3 6 9
elsif (defined $r->{'util_args'}{'before'}) { } 1 5 6
elsif (defined $r->{'util_args'}{'after'}) { } 1 4 5
124 3 $new_fields_idx = $r->{util_args}{at}-1;
125 } elsif (defined $r->{util_args}{before}) {
126 1 for (0..$#{ $r->{input_fields} }) {
127 2 ▶ if ($r->{input_fields}[$_] eq $r->{util_args}{before}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"input_fields"}[$_] eq $r->{"util_args"}{"before"}) 1 1 2
128 1 $new_fields_idx = $_;
129 1 last;
130 }
131 }
132 1 ▶ die [400, "Field '$r->{util_args}{before}' (to add new fields before) not found"]
Branch: 1 branch
BranchTrueFalseTotal
unless defined $new_fields_idx 0 1 1
133 unless defined $new_fields_idx;
134 } elsif (defined $r->{util_args}{after}) {
135 1 for (0..$#{ $r->{input_fields} }) {
136 1 ▶ if ($r->{input_fields}[$_] eq $r->{util_args}{after}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r->{"input_fields"}[$_] eq $r->{"util_args"}{"after"}) 1 0 1
137 1 $new_fields_idx = $_+1;
138 1 last;
139 }
140 }
141 1 ▶ die [400, "Field '$r->{util_args}{after}' (to add new fields after) not found"]
Branch: 1 branch
BranchTrueFalseTotal
unless defined $new_fields_idx 0 1 1
142 unless defined $new_fields_idx;
143 } else {
144 4 $new_fields_idx = @{ $r->{input_fields} };
145 }
146  
147 # for printing the header
148 9 $r->{output_fields} = [@{ $r->{input_fields} }];
149 9 splice @{ $r->{output_fields} }, $new_fields_idx, 0, @{ $r->{util_args}{fields} };
150  
151 9 ▶ $r->{wants_input_row_as_hashref} = 1 if $r->{util_args}{hash};
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"util_args"}{"hash"} 0 9 9
152  
153 # we add the following keys to the stash
154 9 ▶ $r->{code} = compile_eval_code($r->{util_args}{eval} // 'return', 'eval');
Condition100%2/2
$r->{"util_args"}{"eval"} // "return"
l!l
81
MC/DC100%1/1
$r->{"util_args"}{"eval"} // "return"
$r->{"util_args"}{"eval"}
Truth table100%2/2
A
A= $r->{"util_args"}{"eval"}
Aresult
11
00
155 8 $r->{new_fields_idx} = $new_fields_idx;
156 },
157  
158 24 ▶ on_input_data_row => sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
159 24 my $r = shift;
160  
161 24 my @vals;
162 24 ▶ eval { @vals = eval_code($r->{code}, $r, $r->{wants_input_row_as_hashref} ? $r->{input_row_as_hashref} : $r->{input_row}) };
Branch: 1 branch
BranchTrueFalseTotal
$r->{'wants_input_row_as_hashref'} ? : 0 24 24
163 0 ▶ die [500, "Error while adding field(s) '".join(",", @{$r->{util_args}{fields}})."' for row #$r->{input_rownum}: $@"]
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 24 24
164 if $@;
165 24 ▶ if (ref $vals[0] eq 'ARRAY') { @vals = @{ $vals[0] } }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $vals[0] eq "ARRAY") 6 18 24
166 24 splice @{ $r->{input_row} }, $r->{new_fields_idx}, 0,
167 24 ▶ (map { $_ // '' } @vals[0 .. $#{$r->{util_args}{fields}}]);
Condition100%2/2
$_ // ""
l!l
333
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
168 24 $r->{code_print_row}->($r->{input_row});
169 },
170 2 );
171  
172 2 1;
173 # ABSTRACT: Add one or more fields to CSV file
174  
175 __END__
« CSVUtils/csv_lookup_fields.pm ↑ Summary CSVUtils/csv_trim.pm »