lib/JSON/LINQ.pm

filter: Statementstmt 83.0% 865 / 1041 Branchbran 63.7% 279 / 438 Conditioncond 52.9% 63 / 119 MC/DCmcdc 29.1% 21 / 72 Subroutinesub 84.2% 155 / 184 Podpod 96.9% 63 / 65 totaltotal 75.3% 1446 / 1919 CC 268 SCAR 20.7
CC
268
Cov
76%
LastOrDefault
72.0
Single
42.0
SingleOrDefault
42.0
CRAP 7.9
↑ Summary
1 package JSON::LINQ;
2 ######################################################################
3 #
4 # JSON::LINQ - LINQ-style query interface for JSON, JSONL, and LTSV files
5 #
6 # https://metacpan.org/dist/JSON-LINQ
7 #
8 # Copyright (c) 2026 INABA Hitoshi <ina@cpan.org>
9 ######################################################################
10 #
11 # Compatible : Perl 5.005_03 and later
12 # Platform : Windows and UNIX/Linux
13 #
14 ######################################################################
15  
16 11 ▶use 5.00503; # Universal Consensus 1998 for primetools
Subroutine BEGIN: called CC=1 SCAR=0.0
17 # Perl 5.005_03 compatibility for historical toolchains
18 # use 5.008001; # Lancaster Consensus 2013 for toolchains
19  
20 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 0 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
Subroutine BEGIN: called CC=3 SCAR=16.5
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::import) 0 11 11
Condition33%1/3
$] < "5.006" and not defined &warnings::import
!ll&&!rl&&r
1100
MC/DC0%0/2
$] < "5.006" and not defined &warnings::import
$] < "5.006" not defined &warnings::import
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::import
ABresult
0X0
100
111
22 11 ▶use warnings; local $^W = 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 11 ▶BEGIN { pop @INC if $INC[-1] eq '.' }
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $INC[-1] eq "." 0 11 11
24  
25 11 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 11 ▶use vars qw($VERSION $_fh_seq);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 11 $VERSION = '1.02';
29 11 $VERSION = $VERSION;
30 # $VERSION self-assignment suppresses "used only once" warning under strict.
31 11 $_fh_seq = 0;
32 11 $_fh_seq = $_fh_seq;
33 # $_fh_seq self-assignment suppresses "used only once" warning under strict.
34  
35 ###############################################################################
36 # JSON Boolean type objects (merged from mb::JSON)
37 ###############################################################################
38  
39 package JSON::LINQ::Boolean;
40 11 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
41 11 $VERSION = '1.02';
42 11 $VERSION = $VERSION;
43  
44 use overload
45 2 ▶ '0+' => sub { ${ $_[0] } },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
46 2 ▶ q{""} => sub { ${ $_[0] } ? 'true' : 'false' },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
${$_[0];} ? : 1 1 2
47 3 ▶ 'bool' => sub { ${ $_[0] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
48 11 fallback => 1;
49  
50 package JSON::LINQ;
51  
52 11 ▶use vars qw($true $false);
Subroutine BEGIN: called CC=1 SCAR=0.0
53 {
54 11 my $_t = 1; $true = bless \$_t, 'JSON::LINQ::Boolean';
55 11 my $_f = 0; $false = bless \$_f, 'JSON::LINQ::Boolean';
56 }
57  
58 2 ▶sub true { $true }
Subroutine true: called CC=1 SCAR=0.0
Pod documented
59 2 ▶sub false { $false }
Subroutine false: called CC=1 SCAR=0.0
Pod documented
60  
61 ###############################################################################
62 # Internal JSON encoder/decoder (merged from mb::JSON 0.06)
63 ###############################################################################
64  
65 # UTF-8 multibyte pattern
66 11 my $utf8_pat = join '|', (
67 '[\x00-\x7F\x80-\xBF\xC0-\xC1\xF5-\xFF]',
68 '[\xC2-\xDF][\x80-\xBF]',
69 '[\xE0][\xA0-\xBF][\x80-\xBF]',
70 '[\xE1-\xEC][\x80-\xBF][\x80-\xBF]',
71 '[\xED][\x80-\x9F][\x80-\xBF]',
72 '[\xEE-\xEF][\x80-\xBF][\x80-\xBF]',
73 '[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]',
74 '[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]',
75 '[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]',
76 '[\x00-\xFF]',
77 );
78  
79 163 ▶sub _json_decode {
Subroutine _json_decode: called CC=3 SCAR=11.2
80 163 ▶ my $json = defined $_[0] ? $_[0] : $_;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 163 0 163
81 163 my $r = \$json;
82 163 my $val = _parse_value($r);
83 163 $$r =~ s/\A\s+//s;
84 163 ▶ croak "JSON::LINQ::_json_decode: trailing garbage: " . substr($$r, 0, 20)
Branch: 1 branch
BranchTrueFalseTotal
if length $$r 0 163 163
85 if length $$r;
86 163 return $val;
87 }
88  
89 802 ▶sub _parse_value {
Subroutine _parse_value: called CC=9 SCAR=22.1
90 802 my ($r) = @_;
91 802 $$r =~ s/\A\s+//s;
92 802 ▶ croak "JSON::LINQ::_json_decode: unexpected end of input" unless length $$r;
Branch: 1 branch
BranchTrueFalseTotal
unless length $$r 0 802 802
93  
94 802 my $c = substr($$r, 0, 1);
95  
96 802 ▶ if ($c eq '{') { return _parse_object($r) }
Branch: 7 branches
BranchTrueFalseTotal
if ($c eq '{') { } 220 582 802
elsif ($c eq '[') { } 30 552 582
elsif ($c eq '"') { } 237 315 552
elsif ($$r =~ s/\Anull(?=[^a-zA-Z0-9_]|$)//s) { } 1 314 315
elsif ($$r =~ s/\Atrue(?=[^a-zA-Z0-9_]|$)//s) { } 12 302 314
elsif ($$r =~ s/\Afalse(?=[^a-zA-Z0-9_]|$)//s) { } 6 296 302
elsif ($$r =~ s/\A(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)//s) { } 296 0 296
97 30 elsif ($c eq '[') { return _parse_array($r) }
98 237 elsif ($c eq '"') { return _parse_string($r) }
99 1 elsif ($$r =~ s/\Anull(?=[^a-zA-Z0-9_]|$)//s) { return undef }
100 12 elsif ($$r =~ s/\Atrue(?=[^a-zA-Z0-9_]|$)//s) { return $true }
101 6 elsif ($$r =~ s/\Afalse(?=[^a-zA-Z0-9_]|$)//s) { return $false }
102 elsif ($$r =~ s/\A(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)//s) {
103 296 return $1 + 0;
104 }
105 else {
106 0 croak "JSON::LINQ::_json_decode: unexpected token: " . substr($$r, 0, 20);
107 }
108 }
109  
110 220 ▶sub _parse_object {
Subroutine _parse_object: called CC=6 SCAR=18.4
111 220 my ($r) = @_;
112 220 $$r =~ s/\A\{//s;
113 220 my %obj;
114 220 $$r =~ s/\A\s+//s;
115 0 ▶ if ($$r =~ s/\A\}//s) { return { %obj } }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ s/\A\}//s) 0 220 220
116 220 while (1) {
117 552 $$r =~ s/\A\s+//s;
118 552 ▶ croak "JSON::LINQ::_json_decode: expected string key in object"
Branch: 1 branch
BranchTrueFalseTotal
unless $$r =~ /\A"/ 0 552 552
119 unless $$r =~ /\A"/;
120 552 my $key = _parse_string($r);
121 552 $$r =~ s/\A\s+//s;
122 552 ▶ $$r =~ s/\A://s
Branch: 1 branch
BranchTrueFalseTotal
$$r =~ s/\A://s or croak("JSON::LINQ::_json_decode: expected ':' after key '${key}'") 552 0 552
123 or croak "JSON::LINQ::_json_decode: expected ':' after key '$key'";
124 552 my $val = _parse_value($r);
125 552 $obj{$key} = $val;
126 552 $$r =~ s/\A\s+//s;
127 552 ▶ if ($$r =~ s/\A,//s) { next }
Branch: 2 branches
BranchTrueFalseTotal
if ($$r =~ s/\A,//s) { } 332 220 552
elsif ($$r =~ s/\A\}//s) { } 220 0 220
128 220 elsif ($$r =~ s/\A\}//s) { last }
129 0 else { croak "JSON::LINQ::_json_decode: expected ',' or '}' in object" }
130 }
131 220 return { %obj };
132 }
133  
134 30 ▶sub _parse_array {
Subroutine _parse_array: called CC=4 SCAR=14.2
135 30 my ($r) = @_;
136 30 $$r =~ s/\A\[//s;
137 30 my @arr;
138 30 $$r =~ s/\A\s+//s;
139 0 ▶ if ($$r =~ s/\A\]//s) { return [ @arr ] }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ s/\A\]//s) 0 30 30
140 30 while (1) {
141 87 push @arr, _parse_value($r);
142 87 $$r =~ s/\A\s+//s;
143 87 ▶ if ($$r =~ s/\A,//s) { next }
Branch: 2 branches
BranchTrueFalseTotal
if ($$r =~ s/\A,//s) { } 57 30 87
elsif ($$r =~ s/\A\]//s) { } 30 0 30
144 30 elsif ($$r =~ s/\A\]//s) { last }
145 0 else { croak "JSON::LINQ::_json_decode: expected ',' or ']' in array" }
146 }
147 30 return [ @arr ];
148 }
149  
150 11 my %UNESC = (
151 '"' => '"', '\\' => '\\', '/' => '/',
152 'b' => "\x08", 'f' => "\x0C",
153 'n' => "\n", 'r' => "\r", 't' => "\t",
154 );
155  
156 789 ▶sub _parse_string {
Subroutine _parse_string: called CC=5 SCAR=17.6
157 789 my ($r) = @_;
158 789 $$r =~ s/\A"//s;
159 789 my $s = '';
160 789 while (1) {
161 4135 ▶ if ($$r =~ s/\A"//s) { last }
Branch: 4 branches
BranchTrueFalseTotal
if ($$r =~ s/\A"//s) { } 789 3346 4135
elsif ($$r =~ s[\A\\(["\\/bfnrt])][]s) { } 0 3346 3346
elsif ($$r =~ s/\A\\u([0-9a-fA-F]{4})//s) { } 0 3346 3346
elsif ($$r =~ s/\A($utf8_pat)//s) { } 3346 0 3346
162 0 elsif ($$r =~ s/\A\\(["\\\/bfnrt])//s) { $s .= $UNESC{$1} }
163 elsif ($$r =~ s/\A\\u([0-9a-fA-F]{4})//s) {
164 0 $s .= _cp_to_utf8(hex($1));
165 }
166 3346 elsif ($$r =~ s/\A($utf8_pat)//s) { $s .= $1 }
167 0 else { croak "JSON::LINQ::_json_decode: unterminated string" }
168 }
169 789 return $s;
170 }
171  
172 0 ▶sub _cp_to_utf8 {
Subroutine _cp_to_utf8: not called CC=3 SCAR=24.8
173 0 my ($cp) = @_;
174 0 ▶ return chr($cp) if $cp <= 0x7F;
Branch: 1 branch
BranchTrueFalseTotal
if $cp <= 127 0 0 0
175 0 ▶ if ($cp <= 0x7FF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cp <= 2047) 0 0 0
176 0 return chr(0xC0|($cp>>6)) . chr(0x80|($cp&0x3F));
177 }
178 0 return chr(0xE0|($cp>>12))
179 . chr(0x80|(($cp>>6)&0x3F))
180 . chr(0x80|($cp&0x3F));
181 }
182  
183 21 ▶sub _json_encode {
Subroutine _json_encode: called CC=1 SCAR=0.0
184 21 my ($data) = @_;
185 21 return _enc_value($data);
186 }
187  
188 77 ▶sub _enc_value {
Subroutine _enc_value: called CC=8 SCAR=22.9
189 77 my ($v) = @_;
190 77 ▶ return 'null' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 77 77
191 0 ▶ if (ref $v eq 'JSON::LINQ::Boolean') { return $$v ? 'true' : 'false' }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $v eq "JSON::LINQ::Boolean") 0 77 77
$$v ? : 0 0 0
192 0 ▶ if (ref $v eq 'ARRAY') { return '[' . join(',', map { _enc_value($_) } @$v) . ']' }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "ARRAY") 0 77 77
193 77 ▶ if (ref $v eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "HASH") 21 56 77
194 21 my @pairs = map { _enc_string($_) . ':' . _enc_value($v->{$_}) }
195 sort keys %$v;
196 21 return '{' . join(',', @pairs) . '}';
197 }
198 # number: matches JSON number pattern exactly
199 56 ▶ if (!ref $v && $v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $v and $v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s) 36 20 56
Condition66%2/3
not ref $v and $v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s
!ll&&!rl&&r
02036
MC/DC50%1/2
not ref $v and $v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s
not ref $v $v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s
Truth table66%2/3
not(A) and B
A= not ref $vB= $v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s
ABresult
0X0
100
111
200 36 return $v;
201 }
202 20 return _enc_string($v);
203 }
204  
205 76 ▶sub _enc_string {
Subroutine _enc_string: called CC=1 SCAR=0.0
206 76 my ($s) = @_;
207 76 $s =~ s/\\/\\\\/g;
208 76 $s =~ s/"/\\"/g;
209 76 $s =~ s/\x08/\\b/g;
210 76 $s =~ s/\x0C/\\f/g;
211 76 $s =~ s/\n/\\n/g;
212 76 $s =~ s/\r/\\r/g;
213 76 $s =~ s/\t/\\t/g;
214 0 $s =~ s/([\x00-\x1F])/sprintf('\\u%04X', ord($1))/ge;
215 76 return '"' . $s . '"';
216 }
217  
218 ###############################################################################
219 # Constructor and Iterator Infrastructure
220 ###############################################################################
221  
222 358 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
223 358 my($class, $iterator) = @_;
224 358 return bless { iterator => $iterator }, $class;
225 }
226  
227 414 ▶sub iterator {
Subroutine iterator: called CC=2 SCAR=6.9
Pod undocumented
228 414 my $self = $_[0];
229 # If this object was created by _from_snapshot, _factory provides
230 # a fresh iterator closure each time iterator() is called.
231 414 ▶ if (exists $self->{_factory}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"_factory"}) 57 357 414
232 57 return $self->{_factory}->();
233 }
234 357 return $self->{iterator};
235 }
236  
237 ###############################################################################
238 # Data Source Methods
239 ###############################################################################
240  
241 # From - create query from array
242 102 ▶sub From {
Subroutine From: called CC=2 SCAR=7.1
Pod documented
243 102 my($class, $source) = @_;
244  
245 102 ▶ if (ref($source) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $source eq "ARRAY") 102 0 102
246 102 my $i = 0;
247 457 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
248 457 ▶ return undef if $i >= scalar(@$source);
Branch: 1 branch
BranchTrueFalseTotal
if $i >= scalar @$source 93 364 457
249 364 return $source->[$i++];
250 102 });
251 }
252  
253 0 die "From() requires ARRAY reference";
254 }
255  
256 # _open_fh - open a file for reading ('<') or writing ('>') and return a
257 # filehandle reference that works on all supported Perl versions.
258 #
259 # A unique numbered package glob is used on all Perl versions to guarantee
260 # that concurrent From* iterators (e.g. inside Join/GroupJoin) each get their
261 # own IO slot. (\do{local *_} always resolves to *main::_ and causes
262 # IO-slot collision; lexical filehandles via eval-string are avoided because
263 # they are unreliable with a variable $mode on some Windows Perls.)
264 #
265 # $raw: if true, binmode is called after open so that raw bytes are
266 # read/written on all platforms, preventing \r\n <-> \n translation on
267 # Windows. Pass 0 for text-mode files such as CSV, where the OS-level
268 # \r\n -> \n conversion is desired.
269 167 ▶sub _open_fh {
Subroutine _open_fh: called CC=4 SCAR=13.9
270 167 my($mode, $file, $raw) = @_;
271 167 $_fh_seq++;
272 167 my $seq = $_fh_seq;
273 167 my $fhn = "JSON::LINQ::FH::H${seq}";
274 167 ▶ my $arg = ($mode eq '>') ? ">$file" : "< $file";
Branch: 1 branch
BranchTrueFalseTotal
$mode eq '>' ? : 33 134 167
275 11 ▶ { no strict 'refs'; open($fhn, $arg) or die "Cannot open '$file': $!" }
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
open $fhn, $arg or die "Cannot open '${file}': $!" 167 0 167
276 11 ▶ if ($raw) { no strict 'refs'; binmode(*{$fhn}) }
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if ($raw) 111 56 167
277 167 return $fhn;
278 }
279  
280 # FromJSON - read a JSON file containing a top-level array of objects
281 # Each element of the array becomes one item in the sequence.
282 # The file must contain a single JSON array: [ {...}, {...}, ... ]
283 # or a single JSON object (treated as a one-element sequence).
284 24 ▶sub FromJSON {
Subroutine FromJSON: called CC=4 SCAR=14.1
Pod documented
285 24 my($class, $file) = @_;
286  
287 24 my $fhn = _open_fh('<', $file, 1);
288  
289 24 my $content;
290 11 ▶ { no strict 'refs'; local $/; $content = readline(*{$fhn}) }
Subroutine BEGIN: called CC=1 SCAR=0.0
291 11 ▶ { no strict 'refs'; close($fhn) }
Subroutine BEGIN: called CC=1 SCAR=0.0
292  
293 24 my $data = eval { _json_decode($content) };
294 24 ▶ die "JSON::LINQ::FromJSON: cannot parse '$file': $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 24 24
295  
296 24 my $records;
297 24 ▶ if (ref($data) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'ARRAY') { } 24 0 24
elsif (ref $data eq 'HASH') { } 0 0 0
298 24 $records = $data;
299 }
300 elsif (ref($data) eq 'HASH') {
301 0 $records = [ $data ];
302 }
303 else {
304 0 die "JSON::LINQ::FromJSON: '$file' must contain a JSON array or object";
305 }
306  
307 24 my $i = 0;
308 93 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
309 93 ▶ return undef if $i >= scalar(@$records);
Branch: 1 branch
BranchTrueFalseTotal
if $i >= scalar @$records 24 69 93
310 69 return $records->[$i++];
311 24 });
312 }
313  
314 # FromJSONL - read a JSONL (JSON Lines) file
315 # Each line is a separate JSON value (typically an object).
316 # Empty lines and lines beginning with '#' are skipped.
317 # This is memory-efficient for large files: one line at a time.
318 44 ▶sub FromJSONL {
Subroutine FromJSONL: called CC=1 SCAR=0.0
Pod documented
319 44 my($class, $file) = @_;
320  
321 44 my $fhn = _open_fh('<', $file, 1);
322  
323 175 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=6 SCAR=18.3
324 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
325 175 ▶ while (my $line = readline(*{$fhn})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline *{$fhn;})) 133 43 176
326 133 chomp $line;
327 133 $line =~ s/\r\z//; # Strip CR for CRLF files
328 133 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 1 132 133
329 132 ▶ next if $line =~ /\A\s*\z/; # Skip blank lines
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /\A\s*\z/ 0 132 132
330 132 ▶ next if $line =~ /\A\s*#/; # Skip comment lines
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /\A\s*#/ 0 132 132
331  
332 132 my $val = eval { _json_decode($line) };
333 132 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 132 132
334 0 warn "JSON::LINQ::FromJSONL: skipping invalid JSON line: $@";
335 0 next;
336 }
337 132 return $val;
338 }
339 43 close($fhn);
340 43 return undef;
341 44 });
342 }
343  
344 # FromJSONString - create query from a JSON string (array or object)
345 7 ▶sub FromJSONString {
Subroutine FromJSONString: called CC=4 SCAR=14.0
Pod documented
346 7 my($class, $json) = @_;
347  
348 7 my $data = eval { _json_decode($json) };
349 7 ▶ die "JSON::LINQ::FromJSONString: cannot parse JSON: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
350  
351 7 my $records;
352 7 ▶ if (ref($data) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $data eq 'ARRAY') { } 6 1 7
elsif (ref $data eq 'HASH') { } 1 0 1
353 6 $records = $data;
354 }
355 elsif (ref($data) eq 'HASH') {
356 1 $records = [ $data ];
357 }
358 else {
359 0 $records = [ $data ];
360 }
361  
362 7 my $i = 0;
363 26 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
364 26 ▶ return undef if $i >= scalar(@$records);
Branch: 1 branch
BranchTrueFalseTotal
if $i >= scalar @$records 7 19 26
365 19 return $records->[$i++];
366 7 });
367 }
368  
369 ###############################################################################
370 # CSV parsing helpers (RFC 4180 compliant)
371 ###############################################################################
372  
373 # _parse_csv_line - split one CSV line into a list of fields
374 # Handles: quoted fields, embedded commas, escaped double-quotes (""),
375 # configurable separator (default: comma).
376 # Does NOT handle embedded newlines (multi-line quoted fields).
377 176 ▶sub _parse_csv_line {
Subroutine _parse_csv_line: called CC=13 SCAR=25.8
378 176 my($line, $sep) = @_;
379 176 ▶ $sep = ',' unless defined $sep;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sep 0 176 176
380 176 my @fields = ();
381 176 $line =~ s{\r\n\z|\r\z|\n\z}{};
382 176 my $pos = 0;
383 176 my $len = length($line);
384 176 ▶ while ($pos <= $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos <= $len) 507 176 683
385 507 ▶ if ($pos < $len && substr($line, $pos, 1) eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len and substr($line, $pos, 1) eq '"') { } 2 505 507
Condition100%3/3
$pos < $len and substr($line, $pos, 1) eq "\""
!ll&&!rl&&r
25032
MC/DC100%2/2
$pos < $len and substr($line, $pos, 1) eq "\""
$pos < $len substr($line, $pos, 1) eq "\""
Truth table100%3/3
A and B
A= $pos < $lenB= substr($line, $pos, 1) eq "\""
ABresult
0X0
100
111
386 2 $pos++;
387 2 my $field = '';
388 2 ▶ while ($pos < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 22 0 22
389 22 my $c = substr($line, $pos, 1);
390 22 ▶ if ($c eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq '"') { } 4 18 22
391 4 $pos++;
392 4 ▶ if ($pos < $len && substr($line, $pos, 1) eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len and substr($line, $pos, 1) eq '"') { } 2 2 4
Condition66%2/3
$pos < $len and substr($line, $pos, 1) eq "\""
!ll&&!rl&&r
202
MC/DC50%1/2
$pos < $len and substr($line, $pos, 1) eq "\""
$pos < $len substr($line, $pos, 1) eq "\""
Truth table66%2/3
A and B
A= $pos < $lenB= substr($line, $pos, 1) eq "\""
ABresult
0X0
100
111
393 2 $field .= '"';
394 2 $pos++;
395 }
396 else {
397 2 last;
398 }
399 }
400 else {
401 18 $field .= $c;
402 18 $pos++;
403 }
404 }
405 2 push @fields, $field;
406 2 ▶ $pos++ if $pos < $len && substr($line, $pos, 1) eq $sep;
Branch: 1 branch
BranchTrueFalseTotal
if $pos < $len and substr($line, $pos, 1) eq $sep 0 2 2
Condition33%1/3
$pos < $len and substr($line, $pos, 1) eq $sep
!ll&&!rl&&r
200
MC/DC0%0/2
$pos < $len and substr($line, $pos, 1) eq $sep
$pos < $len substr($line, $pos, 1) eq $sep
Truth table33%1/3
A and B
A= $pos < $lenB= substr($line, $pos, 1) eq $sep
ABresult
0X0
100
111
407 }
408 else {
409 505 my $start = $pos;
410 505 ▶ while ($pos < $len && substr($line, $pos, 1) ne $sep) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len and substr($line, $pos, 1) ne $sep) 1876 505 2381
Condition100%3/3
$pos < $len and substr($line, $pos, 1) ne $sep
!ll&&!rl&&r
1763291876
MC/DC100%2/2
$pos < $len and substr($line, $pos, 1) ne $sep
$pos < $len substr($line, $pos, 1) ne $sep
Truth table100%3/3
A and B
A= $pos < $lenB= substr($line, $pos, 1) ne $sep
ABresult
0X0
100
111
411 1876 $pos++;
412 }
413 505 push @fields, substr($line, $start, $pos - $start);
414 505 $pos++;
415 }
416 }
417 176 return @fields;
418 }
419  
420 # _format_csv_field - quote a single value for CSV output if necessary
421 126 ▶sub _format_csv_field {
Subroutine _format_csv_field: called CC=5 SCAR=16.1
422 126 my($value, $sep) = @_;
423 126 ▶ $sep = ',' unless defined $sep;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sep 0 126 126
424 126 ▶ $value = '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 125 126
425 126 ▶ if ($value =~ /["\n\r]/ || index($value, $sep) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /["\n\r]/ or index($value, $sep) != -1) 2 124 126
Condition100%3/3
$value =~ /["\n\r]/ or index($value, $sep) != -1
l!l&&r!l&&!r
11124
MC/DC100%2/2
$value =~ /["\n\r]/ or index($value, $sep) != -1
$value =~ /["\n\r]/ index($value, $sep) != -1
Truth table100%3/3
A or B
A= $value =~ /["\n\r]/B= index($value, $sep) != -1
ABresult
1X1
011
000
426 2 $value =~ s/"/""/g;
427 2 return '"' . $value . '"';
428 }
429 124 return $value;
430 }
431  
432 # FromCSV - read a CSV (Comma-Separated Values) file
433 # The first line is used as the header row (column names) unless the
434 # C<headers> option is supplied.
435 # Options:
436 # sep => $char field separator (default: ',')
437 # headers => \@cols explicit column names (skip auto-detect from file)
438 # skip_header => 1 skip the first line even when headers is given
439 41 ▶sub FromCSV {
Subroutine FromCSV: called CC=5 SCAR=16.1
Pod documented
440 41 my($class, $file, %opts) = @_;
441 41 ▶ my $sep = defined $opts{sep} ? $opts{sep} : ',';
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'sep'} ? : 2 39 41
442 41 my $headers = $opts{headers};
443 41 my $skip = $opts{skip_header};
444  
445 41 my $fhn = _open_fh('<', $file, 0);
446  
447 41 my @cols = ();
448 41 ▶ if (!defined $headers) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $headers) { } 39 2 41
449 39 my $hdr;
450 11 ▶ { no strict 'refs'; $hdr = readline(*{$fhn}) }
Subroutine BEGIN: called CC=1 SCAR=0.0
451 39 ▶ if (defined $hdr) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hdr) 39 0 39
452 39 @cols = _parse_csv_line($hdr, $sep);
453 }
454 }
455 else {
456 2 @cols = @{$headers};
457 2 ▶ if ($skip) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skip) 1 1 2
458 11 ▶ no strict 'refs'; readline(*{$fhn});
Subroutine BEGIN: called CC=1 SCAR=0.0
459 }
460 }
461  
462 176 ▶ my $iter = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
463 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
464 176 my $line = readline(*{$fhn});
465 176 ▶ if (!defined $line) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $line) 39 137 176
466 39 close($fhn);
467 39 return undef;
468 }
469 137 $line =~ s{\r\n\z|\r\z|\n\z}{};
470 137 ▶ return undef if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 137 137
471 137 my @vals = _parse_csv_line($line, $sep);
472 137 my %rec = ();
473 137 for my $i (0 .. $#cols) {
474 396 $rec{ $cols[$i] } = $vals[$i];
475 }
476 137 return { %rec };
477 41 };
478 41 return $class->new($iter);
479 }
480  
481 # FromLTSV - read an LTSV (Labeled Tab-Separated Values) file
482 # Each line is a record of "label:value" fields separated by tabs.
483 # Empty lines are skipped. Memory-efficient: one line at a time.
484 # This method is provided so JSON::LINQ can JOIN with LTSV data sources
485 # without requiring LTSV::LINQ to be installed.
486 25 ▶sub FromLTSV {
Subroutine FromLTSV: called CC=1 SCAR=0.0
Pod documented
487 25 my($class, $file) = @_;
488  
489 25 my $fhn = _open_fh('<', $file, 1);
490  
491 105 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
492 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
493 105 ▶ while (my $line = readline(*{$fhn})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline *{$fhn;})) 89 24 113
494 89 chomp $line;
495 89 $line =~ s/\r\z//; # Remove CR for CRLF files on any platform
496 89 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 8 81 89
497  
498 my %record = map {
499 81 ▶ /\A(.+?):(.*)\z/ ? ($1, $2) : ()
Branch: 1 branch
BranchTrueFalseTotal
/\A(.+?):(.*)\z/ ? : 222 0 222
500 } split /\t/, $line;
501  
502 81 ▶ return { %record } if %record;
Branch: 1 branch
BranchTrueFalseTotal
if %record 81 0 81
503 }
504 24 close($fhn);
505 24 return undef;
506 25 });
507 }
508  
509 # Range - generate sequence of integers
510 1 ▶sub Range {
Subroutine Range: called CC=1 SCAR=0.0
Pod documented
511 1 my($class, $start, $count) = @_;
512  
513 1 my $current = $start;
514 1 my $remaining = $count;
515  
516 6 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
517 6 ▶ return undef if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 1 5 6
518 5 $remaining--;
519 5 return $current++;
520 1 });
521 }
522  
523 # Empty - return empty sequence
524 4 ▶sub Empty {
Subroutine Empty: called CC=1 SCAR=0.0
Pod documented
525 4 my($class) = @_;
526  
527 5 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
528 5 return undef;
529 4 });
530 }
531  
532 # Repeat - repeat element specified number of times
533 0 ▶sub Repeat {
Subroutine Repeat: not called CC=1 SCAR=6.9
Pod documented
534 0 my($class, $element, $count) = @_;
535  
536 0 my $remaining = $count;
537  
538 0 ▶ return $class->new(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
539 0 ▶ return undef if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 0 0 0
540 0 $remaining--;
541 0 return $element;
542 0 });
543 }
544  
545 ###############################################################################
546 # Filtering Methods
547 ###############################################################################
548  
549 # Where - filter elements
550 28 ▶sub Where {
Subroutine Where: called CC=3 SCAR=11.0
Pod documented
551 28 my($self, @args) = @_;
552 28 my $iter = $self->iterator;
553 28 my $class = ref($self);
554  
555 # Support both code reference and DSL form
556 28 my $cond;
557 28 ▶ if (@args == 1 && ref($args[0]) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 1 and ref $args[0] eq 'CODE') { } 9 19 28
Condition66%2/3
@args == 1 and ref $args[0] eq "CODE"
!ll&&!rl&&r
1909
MC/DC50%1/2
@args == 1 and ref $args[0] eq "CODE"
@args == 1 ref $args[0] eq "CODE"
Truth table66%2/3
A and B
A= @args == 1B= ref $args[0] eq "CODE"
ABresult
0X0
100
111
558 9 $cond = $args[0];
559 }
560 else {
561 # DSL form: Where(key => value, ...)
562 19 my %match = @args;
563 80 ▶ $cond = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
564 80 my $row = shift;
565 80 for my $k (keys %match) {
566 83 ▶ return 0 unless defined $row->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{$k} 5 78 83
567 78 ▶ return 0 unless $row->{$k} eq $match{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $row->{$k} eq $match{$k} 38 40 78
568 }
569 37 return 1;
570 19 };
571 }
572  
573 89 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
574 89 while (1) {
575 145 my $item = $iter->();
576 145 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 28 117 145
577 117 ▶ return $item if $cond->($item);
Branch: 1 branch
BranchTrueFalseTotal
if &$cond($item) 61 56 117
578 }
579 28 });
580 }
581  
582 ###############################################################################
583 # Projection Methods
584 ###############################################################################
585  
586 # Select - transform elements
587 26 ▶sub Select {
Subroutine Select: called CC=1 SCAR=0.0
Pod documented
588 26 my($self, $selector) = @_;
589 26 my $iter = $self->iterator;
590 26 my $class = ref($self);
591  
592 129 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
593 129 my $item = $iter->();
594 129 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 26 103 129
595 103 return $selector->($item);
596 26 });
597 }
598  
599 # SelectMany - flatten sequences
600 2 ▶sub SelectMany {
Subroutine SelectMany: called CC=1 SCAR=0.0
Pod documented
601 2 my($self, $selector) = @_;
602 2 my $iter = $self->iterator;
603 2 my $class = ref($self);
604  
605 2 my @buffer;
606  
607 12 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
608 12 while (1) {
609 18 ▶ if (@buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if (@buffer) 10 8 18
610 10 return shift @buffer;
611 }
612  
613 8 my $item = $iter->();
614 8 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 2 6 8
615  
616 6 my $result = $selector->($item);
617 6 ▶ unless (ref($result) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $result eq "ARRAY") 0 6 6
618 0 die "SelectMany: selector must return an ARRAY reference";
619 }
620 6 @buffer = @$result;
621 }
622 2 });
623 }
624  
625 # Concat - concatenate two sequences
626 3 ▶sub Concat {
Subroutine Concat: called CC=1 SCAR=0.0
Pod documented
627 3 my($self, $second) = @_;
628 3 my $class = ref($self);
629  
630 3 my $first_iter = $self->iterator;
631 3 my $second_iter;
632 3 my $first_done = 0;
633  
634 21 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
635 21 ▶ if (!$first_done) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($first_done) 13 8 21
636 13 my $item = $first_iter->();
637 13 ▶ if (defined $item) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $item) 10 3 13
638 10 return $item;
639 }
640 3 $first_done = 1;
641 3 $second_iter = $second->iterator;
642 }
643  
644 11 ▶ return $second_iter ? $second_iter->() : undef;
Branch: 1 branch
BranchTrueFalseTotal
$second_iter ? : 11 0 11
645 3 });
646 }
647  
648 # Zip - combine two sequences element-wise
649 0 ▶sub Zip {
Subroutine Zip: not called CC=1 SCAR=6.9
Pod documented
650 0 my($self, $second, $result_selector) = @_;
651  
652 0 my $iter1 = $self->iterator;
653 0 my $iter2 = $second->iterator;
654 0 my $class = ref($self);
655  
656 0 ▶ return $class->new(sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
657 0 my $item1 = $iter1->();
658 0 my $item2 = $iter2->();
659  
660 # Return undef if either sequence ends
661 0 ▶ return undef unless defined($item1) && defined($item2);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item1 and defined $item2 0 0 0
Condition0%0/3
defined $item1 and defined $item2
!ll&&!rl&&r
000
MC/DC0%0/2
defined $item1 and defined $item2
defined $item1 defined $item2
Truth table0%0/3
A and B
A= defined $item1B= defined $item2
ABresult
0X0
100
111
662  
663 0 return $result_selector->($item1, $item2);
664 0 });
665 }
666  
667 ###############################################################################
668 # Partitioning Methods
669 ###############################################################################
670  
671 # Take - take first N elements
672 6 ▶sub Take {
Subroutine Take: called CC=1 SCAR=0.0
Pod documented
673 6 my($self, $count) = @_;
674 6 my $iter = $self->iterator;
675 6 my $class = ref($self);
676 6 my $taken = 0;
677  
678 19 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
679 19 ▶ return undef if $taken >= $count;
Branch: 1 branch
BranchTrueFalseTotal
if $taken >= $count 6 13 19
680 13 my $item = $iter->();
681 13 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 13 13
682 13 $taken++;
683 13 return $item;
684 6 });
685 }
686  
687 # Skip - skip first N elements
688 1 ▶sub Skip {
Subroutine Skip: called CC=1 SCAR=0.0
Pod documented
689 1 my($self, $count) = @_;
690 1 my $iter = $self->iterator;
691 1 my $class = ref($self);
692 1 my $skipped = 0;
693  
694 4 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
695 4 ▶ while ($skipped < $count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skipped < $count) 2 4 6
696 2 my $item = $iter->();
697 2 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 2 2
698 2 $skipped++;
699 }
700 4 return $iter->();
701 1 });
702 }
703  
704 # TakeWhile - take while condition is true
705 0 ▶sub TakeWhile {
Subroutine TakeWhile: not called CC=1 SCAR=6.9
Pod documented
706 0 my($self, $predicate) = @_;
707 0 my $iter = $self->iterator;
708 0 my $class = ref($self);
709 0 my $done = 0;
710  
711 0 ▶ return $class->new(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
712 0 ▶ return undef if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 0 0 0
713 0 my $item = $iter->();
714 0 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 0 0
715  
716 0 ▶ if ($predicate->($item)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$predicate($item)) { } 0 0 0
717 0 return $item;
718 }
719 else {
720 0 $done = 1;
721 0 return undef;
722 }
723 0 });
724 }
725  
726 # SkipWhile - skip elements while predicate is true
727 0 ▶sub SkipWhile {
Subroutine SkipWhile: not called CC=1 SCAR=6.9
Pod documented
728 0 my($self, $predicate) = @_;
729 0 my $iter = $self->iterator;
730 0 my $class = ref($self);
731 0 my $skipping = 1;
732  
733 0 ▶ return $class->new(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
734 0 while (1) {
735 0 my $item = $iter->();
736 0 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 0 0
737  
738 0 ▶ if ($skipping) {
Branch: 1 branch
BranchTrueFalseTotal
if ($skipping) { } 0 0 0
739 0 ▶ if (!$predicate->($item)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$predicate($item)) 0 0 0
740 0 $skipping = 0;
741 0 return $item;
742 }
743 }
744 else {
745 0 return $item;
746 }
747 }
748 0 });
749 }
750  
751 ###############################################################################
752 # Ordering Methods
753 ###############################################################################
754  
755 # OrderBy - sort ascending (smart: numeric when both keys look numeric)
756 3 ▶sub OrderBy {
Subroutine OrderBy: called CC=1 SCAR=0.0
Pod documented
757 3 my($self, $key_selector) = @_;
758 3 my @items = $self->ToArray();
759 3 return JSON::LINQ::Ordered->_new_ordered(
760 [ @items ],
761 [{ sel => $key_selector, dir => 1, type => 'smart' }]
762 );
763 }
764  
765 # OrderByDescending - sort descending (smart comparison)
766 2 ▶sub OrderByDescending {
Subroutine OrderByDescending: called CC=1 SCAR=0.0
Pod documented
767 2 my($self, $key_selector) = @_;
768 2 my @items = $self->ToArray();
769 2 return JSON::LINQ::Ordered->_new_ordered(
770 [ @items ],
771 [{ sel => $key_selector, dir => -1, type => 'smart' }]
772 );
773 }
774  
775 # OrderByStr - sort ascending by string comparison
776 8 ▶sub OrderByStr {
Subroutine OrderByStr: called CC=1 SCAR=0.0
Pod documented
777 8 my($self, $key_selector) = @_;
778 8 my @items = $self->ToArray();
779 8 return JSON::LINQ::Ordered->_new_ordered(
780 [ @items ],
781 [{ sel => $key_selector, dir => 1, type => 'str' }]
782 );
783 }
784  
785 # OrderByStrDescending - sort descending by string comparison
786 0 ▶sub OrderByStrDescending {
Subroutine OrderByStrDescending: not called CC=1 SCAR=6.9
Pod documented
787 0 my($self, $key_selector) = @_;
788 0 my @items = $self->ToArray();
789 0 return JSON::LINQ::Ordered->_new_ordered(
790 [ @items ],
791 [{ sel => $key_selector, dir => -1, type => 'str' }]
792 );
793 }
794  
795 # OrderByNum - sort ascending by numeric comparison
796 6 ▶sub OrderByNum {
Subroutine OrderByNum: called CC=1 SCAR=0.0
Pod documented
797 6 my($self, $key_selector) = @_;
798 6 my @items = $self->ToArray();
799 6 return JSON::LINQ::Ordered->_new_ordered(
800 [ @items ],
801 [{ sel => $key_selector, dir => 1, type => 'num' }]
802 );
803 }
804  
805 # OrderByNumDescending - sort descending by numeric comparison
806 1 ▶sub OrderByNumDescending {
Subroutine OrderByNumDescending: called CC=1 SCAR=0.0
Pod documented
807 1 my($self, $key_selector) = @_;
808 1 my @items = $self->ToArray();
809 1 return JSON::LINQ::Ordered->_new_ordered(
810 [ @items ],
811 [{ sel => $key_selector, dir => -1, type => 'num' }]
812 );
813 }
814  
815 # Reverse - reverse order
816 1 ▶sub Reverse {
Subroutine Reverse: called CC=1 SCAR=0.0
Pod documented
817 1 my($self) = @_;
818 1 my @items = reverse $self->ToArray();
819 1 my $class = ref($self);
820 1 return $class->From([ @items ]);
821 }
822  
823 ###############################################################################
824 # Grouping Methods
825 ###############################################################################
826  
827 # GroupBy - group elements by key
828 7 ▶sub GroupBy {
Subroutine GroupBy: called CC=3 SCAR=11.0
Pod documented
829 7 my($self, $key_selector, $element_selector) = @_;
830 7 ▶ $element_selector ||= sub { $_[0] };
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition66%2/3
$element_selector ||= sub { $_[0]; }
l!l&&r!l&&!r
160
MC/DC0%0/2
$element_selector ||= sub { $_[0]; }
$element_selector sub { $_[0]; }
Truth table66%2/3
A ||= B
A= $element_selectorB= sub { $_[0]; }
ABresult
1X1
011
000
831  
832 7 my %groups;
833 my @key_order;
834  
835 27 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
836 27 my $item = shift;
837 27 my $key = $key_selector->($item);
838 27 ▶ $key = '' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 27 27
839 27 ▶ unless (exists $groups{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $groups{$key}) 18 9 27
840 18 push @key_order, $key;
841 }
842 27 push @{$groups{$key}}, $element_selector->($item);
843 7 });
844  
845 7 my @result;
846 7 for my $key (@key_order) {
847 push @result, {
848 Key => $key,
849 18 Elements => $groups{$key},
850 };
851 }
852  
853 7 my $class = ref($self);
854 7 return $class->From([ @result ]);
855 }
856  
857 ###############################################################################
858 # Set Operations
859 ###############################################################################
860  
861 # Distinct - remove duplicates
862 6 ▶sub Distinct {
Subroutine Distinct: called CC=1 SCAR=0.0
Pod documented
863 6 my($self, $key_selector) = @_;
864 6 my $iter = $self->iterator;
865 6 my $class = ref($self);
866 6 my %seen;
867  
868 26 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
869 26 while (1) {
870 37 my $item = $iter->();
871 37 ▶ return undef unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 6 31 37
872  
873 31 ▶ my $key = $key_selector ? $key_selector->($item) : _make_key($item);
Branch: 1 branch
BranchTrueFalseTotal
$key_selector ? : 3 28 31
874 31 ▶ $key = '' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 31 31
875  
876 31 ▶ unless ($seen{$key}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seen{$key}++) 20 11 31
877 20 return $item;
878 }
879 }
880 6 });
881 }
882  
883 # Internal helper for set operations - make key from item
884 44 ▶sub _make_key {
Subroutine _make_key: called CC=7 SCAR=30.7
885 44 my($item) = @_;
886  
887 44 ▶ return '' unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 44 44
888  
889 44 ▶ if (ref($item) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $item eq 'HASH') { } 0 44 44
elsif (ref $item eq 'ARRAY') { } 0 44 44
890 0 my @pairs = ();
891 0 for my $k (sort keys %$item) {
892 0 ▶ my $v = defined($item->{$k}) ? $item->{$k} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $item->{$k} ? : 0 0 0
893 0 push @pairs, "$k\x1F$v"; # \x1F = Unit Separator
894 }
895 0 return join("\x1E", @pairs); # \x1E = Record Separator
896 }
897 elsif (ref($item) eq 'ARRAY') {
898 0 ▶ return join("\x1E", map { defined($_) ? $_ : '' } @$item);
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
899 }
900 else {
901 44 return $item;
902 }
903 }
904  
905 # _from_snapshot - internal helper for GroupJoin.
906 36 ▶sub _from_snapshot {
Subroutine _from_snapshot: called CC=2 SCAR=7.0
907 36 my($class_or_self, $aref) = @_;
908  
909 36 ▶ my $class = ref($class_or_self) || $class_or_self;
Condition33%1/3
ref $class_or_self || $class_or_self
l!l&&r!l&&!r
0360
MC/DC0%0/2
ref $class_or_self || $class_or_self
ref $class_or_self $class_or_self
Truth table33%1/3
A || B
A= ref $class_or_selfB= $class_or_self
ABresult
1X1
011
000
910  
911 72 ▶ my $iter_factory = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
912 72 my $i = 0;
913 70 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
914 70 ▶ return undef if $i >= scalar(@$aref);
Branch: 1 branch
BranchTrueFalseTotal
if $i >= scalar @$aref 36 34 70
915 34 return $aref->[$i++];
916 72 };
917 36 };
918  
919 36 my $obj = bless {
920 iterator => $iter_factory->(),
921 _factory => $iter_factory,
922 }, $class;
923  
924 36 return $obj;
925 }
926  
927 # Union - set union with distinct
928 1 ▶sub Union {
Subroutine Union: called CC=1 SCAR=0.0
Pod documented
929 1 my($self, $second, $key_selector) = @_;
930  
931 1 return $self->Concat($second)->Distinct($key_selector);
932 }
933  
934 # Intersect - set intersection
935 1 ▶sub Intersect {
Subroutine Intersect: called CC=1 SCAR=0.0
Pod documented
936 1 my($self, $second, $key_selector) = @_;
937  
938 1 my %second_set = ();
939 4 ▶ $second->ForEach(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
940 4 my $item = shift;
941 4 ▶ my $key = $key_selector ? $key_selector->($item) : _make_key($item);
Branch: 1 branch
BranchTrueFalseTotal
$key_selector ? : 0 4 4
942 4 $second_set{$key} = $item;
943 1 });
944  
945 1 my $class = ref($self);
946 1 my $iter = $self->iterator;
947 1 my %seen = ();
948  
949 3 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=5 SCAR=16.3
950 3 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 4 1 5
951 4 ▶ my $key = $key_selector ? $key_selector->($item) : _make_key($item);
Branch: 1 branch
BranchTrueFalseTotal
$key_selector ? : 0 4 4
952  
953 4 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 0 4 4
954 4 ▶ return $item if exists $second_set{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $second_set{$key} 2 2 4
955 }
956 1 return undef;
957 1 });
958 }
959  
960 # Except - set difference
961 1 ▶sub Except {
Subroutine Except: called CC=1 SCAR=0.0
Pod documented
962 1 my($self, $second, $key_selector) = @_;
963  
964 1 my %second_set = ();
965 4 ▶ $second->ForEach(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
966 4 my $item = shift;
967 4 ▶ my $key = $key_selector ? $key_selector->($item) : _make_key($item);
Branch: 1 branch
BranchTrueFalseTotal
$key_selector ? : 0 4 4
968 4 $second_set{$key} = 1;
969 1 });
970  
971 1 my $class = ref($self);
972 1 my $iter = $self->iterator;
973 1 my %seen = ();
974  
975 3 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=5 SCAR=16.3
976 3 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 4 1 5
977 4 ▶ my $key = $key_selector ? $key_selector->($item) : _make_key($item);
Branch: 1 branch
BranchTrueFalseTotal
$key_selector ? : 0 4 4
978  
979 4 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 0 4 4
980 4 ▶ return $item unless exists $second_set{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $second_set{$key} 2 2 4
981 }
982 1 return undef;
983 1 });
984 }
985  
986 # Join - correlates elements of two sequences
987 24 ▶sub Join {
Subroutine Join: called CC=1 SCAR=0.0
Pod documented
988 24 my($self, $inner, $outer_key_selector, $inner_key_selector, $result_selector) = @_;
989  
990 24 my %inner_hash = ();
991 63 ▶ $inner->ForEach(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
992 63 my $item = shift;
993 63 my $key = $inner_key_selector->($item);
994 63 ▶ $key = _make_key($key) if ref($key);
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 0 63 63
995 63 push @{$inner_hash{$key}}, $item;
996 24 });
997  
998 24 my $class = ref($self);
999 24 my $iter = $self->iterator;
1000 24 my @buffer = ();
1001  
1002 98 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
1003 98 while (1) {
1004 180 ▶ return shift @buffer if @buffer;
Branch: 1 branch
BranchTrueFalseTotal
if @buffer 74 106 180
1005  
1006 106 my $outer_item = $iter->();
1007 106 ▶ return undef unless defined $outer_item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $outer_item 24 82 106
1008  
1009 82 my $key = $outer_key_selector->($outer_item);
1010 82 ▶ $key = _make_key($key) if ref($key);
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 0 82 82
1011  
1012 82 ▶ if (exists $inner_hash{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $inner_hash{$key}) 72 10 82
1013 72 for my $inner_item (@{$inner_hash{$key}}) {
1014 74 push @buffer, $result_selector->($outer_item, $inner_item);
1015 }
1016 }
1017 }
1018 24 });
1019 }
1020  
1021 # GroupJoin - group join (LEFT OUTER JOIN-like operation)
1022 10 ▶sub GroupJoin {
Subroutine GroupJoin: called CC=1 SCAR=0.0
Pod documented
1023 10 my($self, $inner, $outer_key_selector, $inner_key_selector, $result_selector) = @_;
1024 10 my $class = ref($self);
1025 10 my $outer_iter = $self->iterator;
1026  
1027 10 my %inner_lookup = ();
1028 32 ▶ $inner->ForEach(sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
1029 32 my $item = shift;
1030 32 my $key = $inner_key_selector->($item);
1031 32 ▶ $key = _make_key($key) if ref($key);
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 0 32 32
1032 32 ▶ $key = '' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 32 32
1033 32 push @{$inner_lookup{$key}}, $item;
1034 10 });
1035  
1036 46 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
1037 46 my $outer_item = $outer_iter->();
1038 46 ▶ return undef unless defined $outer_item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $outer_item 10 36 46
1039  
1040 36 my $key = $outer_key_selector->($outer_item);
1041 36 ▶ $key = _make_key($key) if ref($key);
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 0 36 36
1042 36 ▶ $key = '' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 36 36
1043  
1044 36 ▶ my $matched_inners = exists $inner_lookup{$key} ? $inner_lookup{$key} : [];
Branch: 1 branch
BranchTrueFalseTotal
exists $inner_lookup{$key} ? : 26 10 36
1045  
1046 36 my @snapshot = @$matched_inners;
1047 36 my $inner_group = $class->_from_snapshot([ @snapshot ]);
1048  
1049 36 return $result_selector->($outer_item, $inner_group);
1050 10 });
1051 }
1052  
1053 ###############################################################################
1054 # Quantifier Methods
1055 ###############################################################################
1056  
1057 # All - test if all elements satisfy condition
1058 2 ▶sub All {
Subroutine All: called CC=3 SCAR=11.0
Pod documented
1059 2 my($self, $predicate) = @_;
1060 2 my $iter = $self->iterator;
1061  
1062 2 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 6 1 7
1063 6 ▶ return 0 unless $predicate->($item);
Branch: 1 branch
BranchTrueFalseTotal
unless &$predicate($item) 1 5 6
1064 }
1065 1 return 1;
1066 }
1067  
1068 # Any - test if any element satisfies condition
1069 6 ▶sub Any {
Subroutine Any: called CC=5 SCAR=16.1
Pod documented
1070 6 my($self, $predicate) = @_;
1071 6 my $iter = $self->iterator;
1072  
1073 6 ▶ if ($predicate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($predicate) { } 4 2 6
1074 4 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 11 2 13
1075 11 ▶ return 1 if $predicate->($item);
Branch: 1 branch
BranchTrueFalseTotal
if &$predicate($item) 2 9 11
1076 }
1077 2 return 0;
1078 }
1079 else {
1080 2 my $item = $iter->();
1081 2 ▶ return defined($item) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $item ? : 1 1 2
1082 }
1083 }
1084  
1085 # Contains - check if sequence contains element
1086 2 ▶sub Contains {
Subroutine Contains: called CC=2 SCAR=8.4
Pod documented
1087 2 my($self, $value, $comparer) = @_;
1088  
1089 2 ▶ if ($comparer) {
Branch: 1 branch
BranchTrueFalseTotal
if ($comparer) { } 0 2 2
1090 0 ▶ return $self->Any(sub { $comparer->($_[0], $value) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1091 }
1092 else {
1093 5 ▶ return $self->Any(sub {
Subroutine __ANON__: called CC=5 SCAR=19.4
1094 5 my $item = $_[0];
1095 5 ▶ return (!defined($item) && !defined($value)) ||
Condition50%6/12
!(defined $item || defined $value) || defined $item && defined $value && $item eq $value
l!l&&r!l&&!r
014
defined $item || defined $value
l!l&&r!l&&!r
500
defined $item and defined $value and $item eq $value
!ll&&!rl&&r
041
defined $item and defined $value
!ll&&!rl&&r
005
MC/DC20%1/5
!(defined $item || defined $value) || defined $item && defined $value && $item eq $value
defined $item defined $value defined $item defined $value $item eq $value
Truth table22%2/9
not(A || B) || C and D and E
A= defined $itemB= defined $valueC= defined $itemD= defined $valueE= $item eq $value
ABCDEresult
00XXX1
1X1111
011111
1X0XX0
1X10X0
1X1100
010XX0
0110X0
011100
1096 (defined($item) && defined($value) && $item eq $value);
1097 2 });
1098 }
1099 }
1100  
1101 # SequenceEqual - compare two sequences for equality
1102 2 ▶sub SequenceEqual {
Subroutine SequenceEqual: called CC=7 SCAR=21.3
Pod documented
1103 2 my($self, $second, $comparer) = @_;
1104 6 ▶ $comparer ||= sub {
Subroutine __ANON__: called CC=5 SCAR=19.4
1105 6 my($a, $b) = @_;
1106 6 ▶ return (!defined($a) && !defined($b)) ||
Condition50%6/12
!(defined $a || defined $b) || defined $a && defined $b && $a eq $b
l!l&&r!l&&!r
051
defined $a || defined $b
l!l&&r!l&&!r
600
defined $a and defined $b and $a eq $b
!ll&&!rl&&r
015
defined $a and defined $b
!ll&&!rl&&r
006
MC/DC20%1/5
!(defined $a || defined $b) || defined $a && defined $b && $a eq $b
defined $a defined $b defined $a defined $b $a eq $b
Truth table22%2/9
not(A || B) || C and D and E
A= defined $aB= defined $bC= defined $aD= defined $bE= $a eq $b
ABCDEresult
00XXX1
1X1111
011111
1X0XX0
1X10X0
1X1100
010XX0
0110X0
011100
1107 (defined($a) && defined($b) && $a eq $b);
1108 2 ▶ };
Condition33%1/3
$comparer ||= sub { my($a, $b) = @_; return !(defined $a || defined $b) || defined $a && defined $b && $a eq $b; }
l!l&&r!l&&!r
020
MC/DC0%0/2
$comparer ||= sub { my($a, $b) = @_; return !(defined $a || defined $b) || defined $a && defined $b && $a eq $b; }
$comparer sub { my($a, $b) = @_; return !(defined $a || defined $b) || defined $a && defined $b && $a eq $b; }
Truth table33%1/3
A ||= B
A= $comparerB= sub { my($a, $b) = @_; return !(defined $a || defined $b) || defined $a && defined $b && $a eq $b; }
ABresult
1X1
011
000
1109  
1110 2 my $iter1 = $self->iterator;
1111 2 my $iter2 = $second->iterator;
1112  
1113 2 while (1) {
1114 7 my $item1 = $iter1->();
1115 7 my $item2 = $iter2->();
1116  
1117 7 ▶ return 1 if !defined($item1) && !defined($item2);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item1 or defined $item2 1 6 7
Condition66%2/3
defined $item1 or defined $item2
l!l&&r!l&&!r
601
MC/DC50%1/2
defined $item1 or defined $item2
defined $item1 defined $item2
Truth table66%2/3
A or B
A= defined $item1B= defined $item2
ABresult
1X1
011
000
1118 6 ▶ return 0 if !defined($item1) || !defined($item2);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item1 and defined $item2 0 6 6
Condition33%1/3
defined $item1 and defined $item2
!ll&&!rl&&r
006
MC/DC0%0/2
defined $item1 and defined $item2
defined $item1 defined $item2
Truth table33%1/3
A and B
A= defined $item1B= defined $item2
ABresult
0X0
100
111
1119 6 ▶ return 0 unless $comparer->($item1, $item2);
Branch: 1 branch
BranchTrueFalseTotal
unless &$comparer($item1, $item2) 1 5 6
1120 }
1121 }
1122  
1123 ###############################################################################
1124 # Element Access Methods
1125 ###############################################################################
1126  
1127 # First - get first element
1128 1 ▶sub First {
Subroutine First: called CC=5 SCAR=20.3
Pod documented
1129 1 my($self, $predicate) = @_;
1130 1 my $iter = $self->iterator;
1131  
1132 1 ▶ if ($predicate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($predicate) { } 1 0 1
1133 1 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 2 0 2
1134 2 ▶ return $item if $predicate->($item);
Branch: 1 branch
BranchTrueFalseTotal
if &$predicate($item) 1 1 2
1135 }
1136 0 die "No element satisfies the condition";
1137 }
1138 else {
1139 0 my $item = $iter->();
1140 0 ▶ return $item if defined $item;
Branch: 1 branch
BranchTrueFalseTotal
if defined $item 0 0 0
1141 0 die "Sequence contains no elements";
1142 }
1143 }
1144  
1145 # FirstOrDefault - get first element or default
1146 0 ▶sub FirstOrDefault {
Subroutine FirstOrDefault: not called CC=5 SCAR=34.0
Pod documented
1147 0 my $self = shift;
1148 0 my($predicate, $default);
1149  
1150 0 ▶ if (@_ >= 2) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ >= 2) { } 0 0 0
elsif (@_ == 1) { } 0 0 0
1151 0 ($predicate, $default) = @_;
1152 }
1153 elsif (@_ == 1) {
1154 0 ▶ if (ref($_[0]) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'CODE') { } 0 0 0
1155 0 $predicate = $_[0];
1156 }
1157 else {
1158 0 $default = $_[0];
1159 }
1160 }
1161  
1162 0 my $result = eval { $self->First($predicate) };
1163 0 ▶ return $@ ? $default : $result;
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 0 0
1164 }
1165  
1166 # Last - get last element
1167 1 ▶sub Last {
Subroutine Last: called CC=5 SCAR=20.9
Pod documented
1168 1 my($self, $predicate) = @_;
1169 1 my @items = $self->ToArray();
1170  
1171 1 ▶ if ($predicate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($predicate) { } 1 0 1
1172 1 ▶ for (my $i = $#items; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 1 0 1
1173 1 ▶ return $items[$i] if $predicate->($items[$i]);
Branch: 1 branch
BranchTrueFalseTotal
if &$predicate($items[$i]) 1 0 1
1174 }
1175 0 die "No element satisfies the condition";
1176 }
1177 else {
1178 0 ▶ die "Sequence contains no elements" unless @items;
Branch: 1 branch
BranchTrueFalseTotal
unless @items 0 0 0
1179 0 return $items[-1];
1180 }
1181 }
1182  
1183 # LastOrDefault - return last element or default
1184 0 ▶sub LastOrDefault {
Subroutine LastOrDefault: not called CC=8 SCAR=42.8
Pod documented
1185 0 my $self = shift;
1186 0 my($predicate, $default);
1187  
1188 0 ▶ if (@_ >= 2) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ >= 2) { } 0 0 0
elsif (@_ == 1) { } 0 0 0
1189 0 ($predicate, $default) = @_;
1190 }
1191 elsif (@_ == 1) {
1192 0 ▶ if (ref($_[0]) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'CODE') { } 0 0 0
1193 0 $predicate = $_[0];
1194 }
1195 else {
1196 0 $default = $_[0];
1197 }
1198 }
1199  
1200 0 my @items = $self->ToArray();
1201  
1202 0 ▶ if ($predicate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($predicate) { } 0 0 0
1203 0 ▶ for (my $i = $#items; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 0 0 0
1204 0 ▶ return $items[$i] if $predicate->($items[$i]);
Branch: 1 branch
BranchTrueFalseTotal
if &$predicate($items[$i]) 0 0 0
1205 }
1206 0 return $default;
1207 }
1208 else {
1209 0 ▶ return @items ? $items[-1] : $default;
Branch: 1 branch
BranchTrueFalseTotal
@items ? : 0 0 0
1210 }
1211 }
1212  
1213 # Single - return the only element
1214 0 ▶sub Single {
Subroutine Single: not called CC=6 SCAR=37.4
Pod documented
1215 0 my($self, $predicate) = @_;
1216 0 my $iter = $self->iterator;
1217 0 my $found;
1218 0 my $count = 0;
1219  
1220 0 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 0 0 0
1221 0 ▶ next if $predicate && !$predicate->($item);
Branch: 1 branch
BranchTrueFalseTotal
if $predicate and not &$predicate($item) 0 0 0
Condition0%0/3
$predicate and not &$predicate($item)
!ll&&!rl&&r
000
MC/DC0%0/2
$predicate and not &$predicate($item)
$predicate not &$predicate($item)
Truth table0%0/3
A and not(B)
A= $predicateB= not &$predicate($item)
ABresult
0X0
100
111
1222  
1223 0 $count++;
1224 0 ▶ if ($count > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count > 1) 0 0 0
1225 0 die "Sequence contains more than one element";
1226 }
1227 0 $found = $item;
1228 }
1229  
1230 0 ▶ die "Sequence contains no elements" if $count == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $count == 0 0 0 0
1231 0 return $found;
1232 }
1233  
1234 # SingleOrDefault - return the only element or undef
1235 0 ▶sub SingleOrDefault {
Subroutine SingleOrDefault: not called CC=6 SCAR=37.4
Pod documented
1236 0 my($self, $predicate) = @_;
1237 0 my $iter = $self->iterator;
1238 0 my $found;
1239 0 my $count = 0;
1240  
1241 0 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 0 0 0
1242 0 ▶ next if $predicate && !$predicate->($item);
Branch: 1 branch
BranchTrueFalseTotal
if $predicate and not &$predicate($item) 0 0 0
Condition0%0/3
$predicate and not &$predicate($item)
!ll&&!rl&&r
000
MC/DC0%0/2
$predicate and not &$predicate($item)
$predicate not &$predicate($item)
Truth table0%0/3
A and not(B)
A= $predicateB= not &$predicate($item)
ABresult
0X0
100
111
1243  
1244 0 $count++;
1245 0 ▶ if ($count > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count > 1) 0 0 0
1246 0 return undef;
1247 }
1248 0 $found = $item;
1249 }
1250  
1251 0 ▶ return $count == 1 ? $found : undef;
Branch: 1 branch
BranchTrueFalseTotal
$count == 1 ? : 0 0 0
1252 }
1253  
1254 # ElementAt - return element at specified index
1255 0 ▶sub ElementAt {
Subroutine ElementAt: not called CC=4 SCAR=30.0
Pod documented
1256 0 my($self, $index) = @_;
1257 0 ▶ die "Index must be non-negative" if $index < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $index < 0 0 0 0
1258  
1259 0 my $iter = $self->iterator;
1260 0 my $current = 0;
1261  
1262 0 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 0 0 0
1263 0 ▶ return $item if $current == $index;
Branch: 1 branch
BranchTrueFalseTotal
if $current == $index 0 0 0
1264 0 $current++;
1265 }
1266  
1267 0 die "Index out of range";
1268 }
1269  
1270 # ElementAtOrDefault - return element at index or undef
1271 0 ▶sub ElementAtOrDefault {
Subroutine ElementAtOrDefault: not called CC=4 SCAR=30.0
Pod documented
1272 0 my($self, $index) = @_;
1273 0 ▶ return undef if $index < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $index < 0 0 0 0
1274  
1275 0 my $iter = $self->iterator;
1276 0 my $current = 0;
1277  
1278 0 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 0 0 0
1279 0 ▶ return $item if $current == $index;
Branch: 1 branch
BranchTrueFalseTotal
if $current == $index 0 0 0
1280 0 $current++;
1281 }
1282  
1283 0 return undef;
1284 }
1285  
1286 ###############################################################################
1287 # Aggregation Methods
1288 ###############################################################################
1289  
1290 # Count - count elements
1291 18 ▶sub Count {
Subroutine Count: called CC=3 SCAR=11.0
Pod documented
1292 18 my($self, $predicate) = @_;
1293  
1294 18 ▶ if ($predicate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($predicate) 1 17 18
1295 1 return $self->Where($predicate)->Count();
1296 }
1297  
1298 17 my $count = 0;
1299 17 my $iter = $self->iterator;
1300 17 ▶ $count++ while defined $iter->();
Branch: 1 branch
BranchTrueFalseTotal
defined &$iter() and do { ++$count } 32 17 49
1301 17 return $count;
1302 }
1303  
1304 # Sum - calculate sum
1305 11 ▶sub Sum {
Subroutine Sum: called CC=2 SCAR=7.0
Pod documented
1306 11 my($self, $selector) = @_;
1307 11 ▶ $selector ||= sub { $_[0] };
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition66%2/3
$selector ||= sub { $_[0]; }
l!l&&r!l&&!r
1010
MC/DC0%0/2
$selector ||= sub { $_[0]; }
$selector sub { $_[0]; }
Truth table66%2/3
A ||= B
A= $selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1308  
1309 11 my $sum = 0;
1310 28 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1311 28 $sum += $selector->(shift);
1312 11 });
1313 11 return $sum;
1314 }
1315  
1316 # Min - find minimum
1317 1 ▶sub Min {
Subroutine Min: called CC=2 SCAR=7.1
Pod documented
1318 1 my($self, $selector) = @_;
1319 0 ▶ $selector ||= sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$selector ||= sub { $_[0]; }
l!l&&r!l&&!r
100
MC/DC0%0/2
$selector ||= sub { $_[0]; }
$selector sub { $_[0]; }
Truth table33%1/3
A ||= B
A= $selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1320  
1321 1 my $min;
1322 5 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1323 5 my $val = $selector->(shift);
1324 5 ▶ $min = $val if !defined($min) || $val < $min;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $min or $val < $min 3 2 5
Condition100%3/3
not defined $min or $val < $min
l!l&&r!l&&!r
122
MC/DC100%2/2
not defined $min or $val < $min
not defined $min $val < $min
Truth table100%3/3
not(A) or B
A= not defined $minB= $val < $min
ABresult
1X1
011
000
1325 1 });
1326 1 return $min;
1327 }
1328  
1329 # Max - find maximum
1330 1 ▶sub Max {
Subroutine Max: called CC=2 SCAR=7.1
Pod documented
1331 1 my($self, $selector) = @_;
1332 0 ▶ $selector ||= sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$selector ||= sub { $_[0]; }
l!l&&r!l&&!r
100
MC/DC0%0/2
$selector ||= sub { $_[0]; }
$selector sub { $_[0]; }
Truth table33%1/3
A ||= B
A= $selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1333  
1334 1 my $max;
1335 5 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1336 5 my $val = $selector->(shift);
1337 5 ▶ $max = $val if !defined($max) || $val > $max;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $max or $val > $max 2 3 5
Condition100%3/3
not defined $max or $val > $max
l!l&&r!l&&!r
113
MC/DC100%2/2
not defined $max or $val > $max
not defined $max $val > $max
Truth table100%3/3
not(A) or B
A= not defined $maxB= $val > $max
ABresult
1X1
011
000
1338 1 });
1339 1 return $max;
1340 }
1341  
1342 # Average - calculate average
1343 1 ▶sub Average {
Subroutine Average: called CC=3 SCAR=11.5
Pod documented
1344 1 my($self, $selector) = @_;
1345 0 ▶ $selector ||= sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$selector ||= sub { $_[0]; }
l!l&&r!l&&!r
100
MC/DC0%0/2
$selector ||= sub { $_[0]; }
$selector sub { $_[0]; }
Truth table33%1/3
A ||= B
A= $selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1346  
1347 1 my $sum = 0;
1348 1 my $count = 0;
1349 5 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1350 5 $sum += $selector->(shift);
1351 5 $count++;
1352 1 });
1353  
1354 1 ▶ die "Sequence contains no elements" if $count == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $count == 0 0 1 1
1355 1 return $sum / $count;
1356 }
1357  
1358 # AverageOrDefault - calculate average or return undef if empty
1359 1 ▶sub AverageOrDefault {
Subroutine AverageOrDefault: called CC=3 SCAR=13.6
Pod documented
1360 1 my($self, $selector) = @_;
1361 0 ▶ $selector ||= sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$selector ||= sub { $_[0]; }
l!l&&r!l&&!r
010
MC/DC0%0/2
$selector ||= sub { $_[0]; }
$selector sub { $_[0]; }
Truth table33%1/3
A ||= B
A= $selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1362  
1363 1 my $sum = 0;
1364 1 my $count = 0;
1365 0 ▶ $self->ForEach(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1366 0 $sum += $selector->(shift);
1367 0 $count++;
1368 1 });
1369  
1370 1 ▶ return undef if $count == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $count == 0 1 0 1
1371 0 return $sum / $count;
1372 }
1373  
1374 # Aggregate - apply accumulator function over sequence
1375 3 ▶sub Aggregate {
Subroutine Aggregate: called CC=7 SCAR=19.5
Pod documented
1376 3 my($self, @args) = @_;
1377  
1378 3 my($seed, $func, $result_selector);
1379  
1380 3 ▶ if (@args == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@args == 1) { } 1 2 3
elsif (@args == 2) { } 1 1 2
elsif (@args == 3) { } 1 0 1
1381 1 $func = $args[0];
1382 1 my $iter = $self->iterator;
1383 1 $seed = $iter->();
1384 1 ▶ die "Sequence contains no elements" unless defined $seed;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $seed 0 1 1
1385  
1386 1 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 3 1 4
1387 3 $seed = $func->($seed, $item);
1388 }
1389 }
1390 elsif (@args == 2) {
1391 1 ($seed, $func) = @args;
1392 3 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1393 3 $seed = $func->($seed, shift);
1394 1 });
1395 }
1396 elsif (@args == 3) {
1397 1 ($seed, $func, $result_selector) = @args;
1398 3 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1399 3 $seed = $func->($seed, shift);
1400 1 });
1401 }
1402 else {
1403 0 die "Invalid number of arguments for Aggregate";
1404 }
1405  
1406 3 ▶ return $result_selector ? $result_selector->($seed) : $seed;
Branch: 1 branch
BranchTrueFalseTotal
$result_selector ? : 1 2 3
1407 }
1408  
1409 ###############################################################################
1410 # Conversion Methods
1411 ###############################################################################
1412  
1413 # ToArray - convert to array
1414 174 ▶sub ToArray {
Subroutine ToArray: called CC=2 SCAR=6.9
Pod documented
1415 174 my($self) = @_;
1416 174 my @result;
1417 174 my $iter = $self->iterator;
1418  
1419 174 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 529 174 703
1420 529 push @result, $item;
1421 }
1422 174 return @result;
1423 }
1424  
1425 # ToList - convert to array reference
1426 0 ▶sub ToList {
Subroutine ToList: not called CC=1 SCAR=6.9
Pod documented
1427 0 my($self) = @_;
1428 0 return [$self->ToArray()];
1429 }
1430  
1431 # ToDictionary - convert sequence to hash reference
1432 1 ▶sub ToDictionary {
Subroutine ToDictionary: called CC=2 SCAR=7.2
Pod documented
1433 1 my($self, $key_selector, $value_selector) = @_;
1434  
1435 0 ▶ $value_selector ||= sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$value_selector ||= sub { $_[0]; }
l!l&&r!l&&!r
100
MC/DC0%0/2
$value_selector ||= sub { $_[0]; }
$value_selector sub { $_[0]; }
Truth table33%1/3
A ||= B
A= $value_selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1436  
1437 1 my %dictionary = ();
1438  
1439 4 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1440 4 my $item = shift;
1441 4 my $key = $key_selector->($item);
1442 4 my $value = $value_selector->($item);
1443  
1444 4 ▶ $key = '' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 4 4
1445 4 $dictionary{$key} = $value;
1446 1 });
1447  
1448 1 return { %dictionary };
1449 }
1450  
1451 # ToLookup - convert sequence to hash of arrays
1452 2 ▶sub ToLookup {
Subroutine ToLookup: called CC=2 SCAR=7.2
Pod documented
1453 2 my($self, $key_selector, $value_selector) = @_;
1454  
1455 0 ▶ $value_selector ||= sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$value_selector ||= sub { $_[0]; }
l!l&&r!l&&!r
200
MC/DC0%0/2
$value_selector ||= sub { $_[0]; }
$value_selector sub { $_[0]; }
Truth table33%1/3
A ||= B
A= $value_selectorB= sub { $_[0]; }
ABresult
1X1
011
000
1456  
1457 2 my %lookup = ();
1458  
1459 8 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1460 8 my $item = shift;
1461 8 my $key = $key_selector->($item);
1462 8 my $value = $value_selector->($item);
1463  
1464 8 ▶ $key = '' unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 8 8
1465 8 push @{$lookup{$key}}, $value;
1466 2 });
1467  
1468 2 return { %lookup };
1469 }
1470  
1471 # DefaultIfEmpty - return default value if empty
1472 2 ▶sub DefaultIfEmpty {
Subroutine DefaultIfEmpty: called CC=2 SCAR=6.9
Pod documented
1473 2 my($self, $default_value) = @_;
1474 2 my $has_default_arg = @_ > 1;
1475 2 ▶ if (!$has_default_arg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_default_arg) 0 2 2
1476 0 $default_value = undef;
1477 }
1478  
1479 2 my $class = ref($self);
1480 2 my $iter = $self->iterator;
1481 2 my $has_elements = 0;
1482 2 my $returned_default = 0;
1483  
1484 6 ▶ return $class->new(sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1485 6 my $item = $iter->();
1486 6 ▶ if (defined $item) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $item) 3 3 6
1487 3 $has_elements = 1;
1488 3 return $item;
1489 }
1490  
1491 3 ▶ if (!$has_elements && !$returned_default) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_elements or $returned_default) 1 2 3
Condition100%3/3
$has_elements or $returned_default
l!l&&r!l&&!r
111
MC/DC100%2/2
$has_elements or $returned_default
$has_elements $returned_default
Truth table100%3/3
A or B
A= $has_elementsB= $returned_default
ABresult
1X1
011
000
1492 1 $returned_default = 1;
1493 1 return $default_value;
1494 }
1495  
1496 2 return undef;
1497 2 });
1498 }
1499  
1500 # ToJSON - write sequence as a JSON array file
1501 # Each element is encoded as JSON; the result is a JSON array.
1502 5 ▶sub ToJSON {
Subroutine ToJSON: called CC=1 SCAR=0.0
Pod documented
1503 5 my($self, $file) = @_;
1504  
1505 5 my $fhn = _open_fh('>', $file, 1);
1506  
1507 11 ▶ { no strict 'refs'; print {*{$fhn}} "[\n" }
Subroutine BEGIN: called CC=1 SCAR=0.0
1508 5 my $first = 1;
1509 13 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1510 13 my $record = shift;
1511 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1512 13 ▶ print {*{$fhn}} ",\n" unless $first;
Branch: 1 branch
BranchTrueFalseTotal
unless $first 8 5 13
1513 13 $first = 0;
1514 13 print {*{$fhn}} _json_encode($record);
1515 5 });
1516 11 ▶ { no strict 'refs'; print {*{$fhn}} "\n]\n" }
Subroutine BEGIN: called CC=1 SCAR=0.0
1517  
1518 11 ▶ { no strict 'refs'; close($fhn) }
Subroutine BEGIN: called CC=1 SCAR=0.0
1519 5 return 1;
1520 }
1521  
1522 # ToJSONL - write sequence as a JSONL (JSON Lines) file
1523 # Each element is encoded as one line of JSON.
1524 # This is streaming-friendly and memory-efficient.
1525 3 ▶sub ToJSONL {
Subroutine ToJSONL: called CC=1 SCAR=0.0
Pod documented
1526 3 my($self, $file) = @_;
1527  
1528 3 my $fhn = _open_fh('>', $file, 1);
1529  
1530 8 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1531 8 my $record = shift;
1532 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1533 8 print {*{$fhn}} _json_encode($record), "\n";
1534 3 });
1535  
1536 11 ▶ { no strict 'refs'; close($fhn) }
Subroutine BEGIN: called CC=1 SCAR=0.0
1537 3 return 1;
1538 }
1539  
1540 # ToLTSV - write sequence as an LTSV (Labeled Tab-Separated Values) file.
1541 # Each element must be a HASH reference.
1542 # Tab/CR/LF in values are sanitized to a single space to keep the file
1543 # structurally valid. This method is provided so a JSON::LINQ pipeline
1544 # can emit LTSV output without requiring LTSV::LINQ.
1545 #
1546 # Options (key => value pairs after $filename):
1547 # label_order => \@labels emit only these labels in this order;
1548 # labels not present in the record are skipped.
1549 # headers => \@labels alias for label_order.
1550 #
1551 # Without label_order/headers, all keys are emitted alphabetically.
1552 10 ▶sub ToLTSV {
Subroutine ToLTSV: called CC=3 SCAR=11.0
Pod documented
1553 10 my($self, $file, %opt) = @_;
1554  
1555 # Resolve label_order / headers alias
1556 10 ▶ my $label_order = $opt{label_order} || $opt{headers} || undef;
Condition100%5/5
$opt{'label_order'} || $opt{'headers'} || undef
l!l
37
$opt{"label_order"} or $opt{"headers"}
l!l&&r!l&&!r
217
MC/DC100%2/2
$opt{'label_order'} || $opt{'headers'} || undef
$opt{"label_order"} $opt{"headers"}
Truth table100%3/3
A or B
A= $opt{"label_order"}B= $opt{"headers"}
ABresult
1X1
011
000
1557  
1558 10 my $fhn = _open_fh('>', $file, 1);
1559  
1560 17 ▶ $self->ForEach(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1561 17 my $record = shift;
1562 # LTSV spec: tab is the field separator; newline terminates the record.
1563 # Sanitize values to prevent structural corruption of the output file.
1564 my @keys = $label_order
1565 17 ▶ ? grep { exists $record->{$_} } @$label_order
Branch: 1 branch
BranchTrueFalseTotal
$label_order ? : 3 14 17
1566 : sort keys %$record;
1567 my $line = join("\t", map {
1568 17 ▶ my $v = defined($record->{$_}) ? $record->{$_} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $record->{$_} ? : 41 1 42
1569 42 $v =~ s/[\t\n\r]/ /g;
1570 42 "$_:$v"
1571 } @keys);
1572 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1573 17 print {*{$fhn}} $line, "\n";
1574 10 });
1575  
1576 11 ▶ { no strict 'refs'; close($fhn) }
Subroutine BEGIN: called CC=1 SCAR=0.0
1577 10 return 1;
1578 }
1579  
1580 ###############################################################################
1581 # CSV Output
1582 ###############################################################################
1583  
1584 # ToCSV - write the sequence as a CSV file.
1585 # Elements that are HASH references are written as named-column rows;
1586 # scalar elements are written one-per-line without a header.
1587 #
1588 # Options (key => value pairs after $filename):
1589 # sep => $char field separator (default: ',')
1590 # headers => \@cols emit only these columns in this order
1591 # label_order => \@cols alias for headers
1592 # no_header => 1 suppress the header row entirely
1593 15 ▶sub ToCSV {
Subroutine ToCSV: called CC=14 SCAR=26.8
Pod documented
1594 15 my($self, $file, %opts) = @_;
1595 15 ▶ my $sep = defined $opts{sep} ? $opts{sep} : ',';
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'sep'} ? : 1 14 15
1596 my $headers = defined $opts{headers} ? $opts{headers}
1597 : defined $opts{label_order} ? $opts{label_order}
1598 15 ▶ : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $opts{'headers'} ? : 9 6 15
defined $opts{'label_order'} ? : 2 4 6
1599 15 my $no_header = $opts{no_header};
1600  
1601 # Materialise the sequence so we can inspect the first element before
1602 # writing the header.
1603 15 my @items = ();
1604 15 my $iter = $self->iterator;
1605 15 ▶ while (defined(my $e = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $e = &$iter())) 31 15 46
1606 31 push @items, $e;
1607 }
1608  
1609 15 my $fhn = _open_fh('>', $file, 0);
1610  
1611 15 ▶ unless ($no_header) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($no_header) 14 1 15
1612 14 my @cols = ();
1613 14 ▶ if (defined $headers) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $headers) { } 10 4 14
elsif (@items and ref $items[0] eq 'HASH') { } 4 0 4
1614 10 @cols = @{$headers};
1615 }
1616 ▶ elsif (@items && ref($items[0]) eq 'HASH') {
Condition33%1/3
@items and ref $items[0] eq "HASH"
!ll&&!rl&&r
004
MC/DC0%0/2
@items and ref $items[0] eq "HASH"
@items ref $items[0] eq "HASH"
Truth table33%1/3
A and B
A= @itemsB= ref $items[0] eq "HASH"
ABresult
0X0
100
111
1617 4 @cols = sort keys %{ $items[0] };
1618 }
1619  
1620 14 ▶ if (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols) 14 0 14
1621 11 ▶ { no strict 'refs'; print {*{$fhn}} join($sep, map { _format_csv_field($_, $sep) } @cols) . "\n" }
Subroutine BEGIN: called CC=1 SCAR=0.0
1622 14 for my $item (@items) {
1623 29 ▶ if (ref($item) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item eq 'HASH') { } 29 0 29
1624 11 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1625 29 print {*{$fhn}} join($sep, map {
1626 29 _format_csv_field($item->{$_}, $sep)
1627 } @cols) . "\n";
1628 }
1629 else {
1630 0 ▶ no strict 'refs'; print {*{$fhn}} _format_csv_field($item, $sep) . "\n";
Subroutine BEGIN: called CC=1 SCAR=1.2
1631 }
1632 }
1633 11 ▶ { no strict 'refs'; close($fhn) }
Subroutine BEGIN: called CC=1 SCAR=0.0
1634 14 return 1;
1635 }
1636 # else: scalar sequence with no header -- fall through to no_header path
1637 }
1638  
1639 # no_header path (or scalar sequence)
1640 1 for my $item (@items) {
1641 2 ▶ if (ref($item) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item eq 'HASH') { } 2 0 2
1642 2 my @cols = sort keys %{$item};
1643 11 ▶ { no strict 'refs'; print {*{$fhn}} join($sep, map {
Subroutine BEGIN: called CC=1 SCAR=0.0
1644 2 _format_csv_field($item->{$_}, $sep)
1645 } @cols) . "\n" }
1646 }
1647 else {
1648 0 ▶ { no strict 'refs'; print {*{$fhn}} _format_csv_field($item, $sep) . "\n" }
Subroutine BEGIN: called CC=1 SCAR=1.7
1649 }
1650 }
1651 11 ▶ { no strict 'refs'; close($fhn) }
Subroutine BEGIN: called CC=1 SCAR=0.0
1652 1 return 1;
1653 }
1654  
1655 ###############################################################################
1656 # Utility Methods
1657 ###############################################################################
1658  
1659 # ForEach - execute action for each element
1660 81 ▶sub ForEach {
Subroutine ForEach: called CC=2 SCAR=6.9
Pod documented
1661 81 my($self, $action) = @_;
1662 81 my $iter = $self->iterator;
1663  
1664 81 ▶ while (defined(my $item = $iter->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $item = &$iter())) 229 81 310
1665 229 $action->($item);
1666 }
1667 81 return;
1668 }
1669  
1670 11 1;
1671  
1672 ######################################################################
1673 #
1674 # JSON::LINQ::Ordered - Ordered query supporting ThenBy/ThenByDescending
1675 #
1676 # Returned by OrderBy* methods. Inherits all JSON::LINQ methods via @ISA.
1677 # Stability guarantee: Schwartzian-Transform stable sort, all Perl versions.
1678 #
1679 ######################################################################
1680  
1681 package JSON::LINQ::Ordered;
1682  
1683 11 @JSON::LINQ::Ordered::ISA = ('JSON::LINQ');
1684  
1685 26 ▶sub _new_ordered {
Subroutine _new_ordered: called CC=1 SCAR=0.0
1686 26 my($class, $items, $specs) = @_;
1687 return bless {
1688 _items => $items,
1689 _specs => $specs,
1690 21 ▶ _factory => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1691 21 my @sorted = _perform_sort($items, $specs);
1692 21 my $i = 0;
1693 21 ▶ return sub { $i < scalar(@sorted) ? $sorted[$i++] : undef };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$i < scalar @sorted ? : 92 20 112
1694 },
1695 26 }, $class;
1696 }
1697  
1698 21 ▶sub _perform_sort {
Subroutine _perform_sort: called CC=5 SCAR=16.1
1699 21 my($items, $specs) = @_;
1700  
1701 my @decorated = map {
1702 95 my $idx = $_;
1703 95 my $item = $items->[$idx];
1704 95 my @keys = map { _extract_key($_->{sel}->($item), $_->{type}) } @{$specs};
1705 95 [$idx, [ @keys ], $item]
1706 21 } 0 .. $#{$items};
1707  
1708 my @sorted_dec = sort {
1709 21 my $r = 0;
1710 135 for my $i (0 .. $#{$specs}) {
1711 156 my $cmp = _compare_keys($a->[1][$i], $b->[1][$i], $specs->[$i]{type});
1712 156 ▶ if ($specs->[$i]{dir} < 0) { $cmp = -$cmp }
Branch: 1 branch
BranchTrueFalseTotal
if ($specs->[$i]{"dir"} < 0) 26 130 156
1713 156 ▶ if ($cmp != 0) { $r = $cmp; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($cmp != 0) 128 28 156
1714 }
1715 135 ▶ $r != 0 ? $r : ($a->[0] <=> $b->[0]);
Branch: 1 branch
BranchTrueFalseTotal
$r != 0 ? : 128 7 135
1716 } @decorated;
1717  
1718 21 return map { $_->[2] } @sorted_dec;
1719 }
1720  
1721 125 ▶sub _extract_key {
Subroutine _extract_key: called CC=7 SCAR=19.8
1722 125 my($val, $type) = @_;
1723 125 ▶ $val = '' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 125 125
1724 125 ▶ if ($type eq 'num') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'num') { } 40 85 125
elsif ($type eq 'str') { } 59 26 85
1725 40 ▶ return defined($val) && length($val) ? $val + 0 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $val && length $val ? : 40 0 40
Condition33%1/3
defined $val and length $val
!ll&&!rl&&r
0040
MC/DC0%0/2
defined $val and length $val
defined $val length $val
Truth table33%1/3
A and B
A= defined $valB= length $val
ABresult
0X0
100
111
1726 }
1727 elsif ($type eq 'str') {
1728 59 return "$val";
1729 }
1730 else {
1731 26 my $t = $val;
1732 26 $t =~ s/^\s+|\s+$//g;
1733 26 ▶ if ($t =~ /^[+-]?(?:\d+\.?\d*|\d*\.\d+)(?:[eE][+-]?\d+)?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t =~ /^[+-]?(?:\d+\.?\d*|\d*\.\d+)(?:[eE][+-]?\d+)?$/) { } 16 10 26
1734 16 return [0, $t + 0];
1735 }
1736 else {
1737 10 return [1, "$val"];
1738 }
1739 }
1740 }
1741  
1742 156 ▶sub _compare_keys {
Subroutine _compare_keys: called CC=7 SCAR=19.9
1743 156 my($ka, $kb, $type) = @_;
1744 156 ▶ if ($type eq 'num') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'num') { } 47 109 156
elsif ($type eq 'str') { } 71 38 109
1745 47 return $ka <=> $kb;
1746 }
1747 elsif ($type eq 'str') {
1748 71 return $ka cmp $kb;
1749 }
1750 else {
1751 38 my $fa = $ka->[0]; my $va = $ka->[1];
1752 38 my $fb = $kb->[0]; my $vb = $kb->[1];
1753 38 ▶ if ($fa == 0 && $fb == 0) { return $va <=> $vb }
Branch: 2 branches
BranchTrueFalseTotal
if ($fa == 0 and $fb == 0) { } 23 15 38
elsif ($fa == 1 and $fb == 1) { } 15 0 15
Condition66%2/3
$fa == 0 and $fb == 0
!ll&&!rl&&r
15023
MC/DC50%1/2
$fa == 0 and $fb == 0
$fa == 0 $fb == 0
Truth table66%2/3
A and B
A= $fa == 0B= $fb == 0
ABresult
0X0
100
111
1754 15 ▶ elsif ($fa == 1 && $fb == 1) { return $va cmp $vb }
Condition33%1/3
$fa == 1 and $fb == 1
!ll&&!rl&&r
0015
MC/DC0%0/2
$fa == 1 and $fb == 1
$fa == 1 $fb == 1
Truth table33%1/3
A and B
A= $fa == 1B= $fb == 1
ABresult
0X0
100
111
1755 0 else { return $fa <=> $fb }
1756 }
1757 }
1758  
1759 6 ▶sub _thenby {
Subroutine _thenby: called CC=1 SCAR=0.0
1760 6 my($self, $key_selector, $dir, $type) = @_;
1761 6 my @new_specs = (@{$self->{_specs}}, { sel => $key_selector, dir => $dir, type => $type });
1762 6 return JSON::LINQ::Ordered->_new_ordered($self->{_items}, [ @new_specs ]);
1763 }
1764  
1765 0 ▶sub ThenBy { my($s, $k)=@_; $s->_thenby($k, 1, 'smart') }
Subroutine ThenBy: not called CC=1 SCAR=6.9
1766 0 ▶sub ThenByDescending { my($s, $k)=@_; $s->_thenby($k, -1, 'smart') }
Subroutine ThenByDescending: not called CC=1 SCAR=6.9
1767 4 ▶sub ThenByStr { my($s, $k)=@_; $s->_thenby($k, 1, 'str') }
Subroutine ThenByStr: called CC=1 SCAR=0.0
1768 0 ▶sub ThenByStrDescending { my($s, $k)=@_; $s->_thenby($k, -1, 'str') }
Subroutine ThenByStrDescending: not called CC=1 SCAR=6.9
1769 0 ▶sub ThenByNum { my($s, $k)=@_; $s->_thenby($k, 1, 'num') }
Subroutine ThenByNum: not called CC=1 SCAR=6.9
1770 2 ▶sub ThenByNumDescending { my($s, $k)=@_; $s->_thenby($k, -1, 'num') }
Subroutine ThenByNumDescending: called CC=1 SCAR=0.0
1771  
1772 11 1;
1773  
1774 =encoding utf-8
1775  
1776 =head1 NAME
1777  
1778 JSON::LINQ - LINQ-style query interface for JSON, JSONL, LTSV, and CSV files
1779  
1780 =head1 VERSION
1781  
1782 Version 1.02
1783  
1784 =head1 SYNOPSIS
1785  
1786 use JSON::LINQ;
1787  
1788 # Read JSON file (array of objects) and query
1789 my @results = JSON::LINQ->FromJSON("users.json")
1790 ->Where(sub { $_[0]{age} >= 18 })
1791 ->Select(sub { $_[0]{name} })
1792 ->Distinct()
1793 ->ToArray();
1794  
1795 # Read JSONL (JSON Lines) file - one JSON object per line
1796 my @errors = JSON::LINQ->FromJSONL("events.jsonl")
1797 ->Where(sub { $_[0]{level} eq 'ERROR' })
1798 ->ToArray();
1799  
1800 # DSL syntax for simple filtering
1801 my @active = JSON::LINQ->FromJSON("users.json")
1802 ->Where(status => 'active')
1803 ->ToArray();
1804  
1805 # Grouping and aggregation
1806 my @stats = JSON::LINQ->FromJSON("orders.json")
1807 ->GroupBy(sub { $_[0]{category} })
1808 ->Select(sub {
1809 my $g = shift;
1810 return {
1811 Category => $g->{Key},
1812 Count => scalar(@{$g->{Elements}}),
1813 Total => JSON::LINQ->From($g->{Elements})
1814 ->Sum(sub { $_[0]{amount} }),
1815 };
1816 })
1817 ->OrderByDescending(sub { $_[0]{Total} })
1818 ->ToArray();
1819  
1820 # Write results back as JSON or JSONL
1821 JSON::LINQ->From(\@results)->ToJSON("output.json");
1822 JSON::LINQ->From(\@results)->ToJSONL("output.jsonl");
1823  
1824 # Read/write CSV files (Comma-Separated Values)
1825 my @rows = JSON::LINQ->FromCSV("access.csv")
1826 ->Where(sub { $_[0]{status} eq '200' })
1827 ->ToArray();
1828 JSON::LINQ->From(\@rows)->ToCSV("filtered.csv");
1829  
1830 # JOIN a JSON file (main) with a CSV lookup table
1831 my $depts = JSON::LINQ->FromCSV("departments.csv");
1832 my @joined = JSON::LINQ->FromJSON("employees.json")
1833 ->Join($depts,
1834 sub { $_[0]{dept_id} },
1835 sub { $_[0]{id} },
1836 sub { { name => $_[0]{name}, dept => $_[1]{name} } })
1837 ->ToArray();
1838  
1839 # CSV to JSON conversion
1840 JSON::LINQ->FromCSV("data.csv")
1841 ->Where(sub { $_[0]{active} eq '1' })
1842 ->ToJSON("active.json");
1843  
1844 # Read/write LTSV files (Labeled Tab-Separated Values)
1845 my @rows = JSON::LINQ->FromLTSV("access.ltsv")
1846 ->Where(sub { $_[0]{status} eq '200' })
1847 ->ToArray();
1848 JSON::LINQ->From(\@rows)->ToLTSV("filtered.ltsv");
1849  
1850 # JOIN a JSON file (main) with an LTSV file (sub-table)
1851 my $depts = JSON::LINQ->FromLTSV("departments.ltsv");
1852 my @joined = JSON::LINQ->FromJSON("employees.json")
1853 ->Join($depts,
1854 sub { $_[0]{dept_id} },
1855 sub { $_[0]{id} },
1856 sub { { name => $_[0]{name}, dept => $_[1]{name} } })
1857 ->ToArray();
1858  
1859 # JOIN an LTSV file (main) with a JSON file (sub-table)
1860 my $prices = JSON::LINQ->FromJSON("prices.json");
1861 my @priced = JSON::LINQ->FromLTSV("orders.ltsv")
1862 ->Join($prices,
1863 sub { $_[0]{sku} },
1864 sub { $_[0]{sku} },
1865 sub { { order_id => $_[0]{id},
1866 amount => $_[0]{qty} * $_[1]{price} } })
1867 ->ToArray();
1868  
1869 # Boolean values
1870 my $rec = { active => JSON::LINQ::true, count => 0 };
1871 JSON::LINQ->From([$rec])->ToJSON("output.json");
1872 # ToJSON encodes as: {"active":true,"count":0}
1873  
1874 =head1 TABLE OF CONTENTS
1875  
1876 =over 4
1877  
1878 =item * L</DESCRIPTION>
1879  
1880 =item * L</INCLUDED DOCUMENTATION> -- eg/ samples and doc/ cheat sheets
1881  
1882 =item * L</METHODS> -- Complete method reference (67 methods)
1883  
1884 =item * L</EXAMPLES> -- Practical examples
1885  
1886 =item * L</FEATURES> -- Lazy evaluation, method chaining, DSL
1887  
1888 =item * L</ARCHITECTURE> -- Iterator design, execution flow
1889  
1890 =item * L</COMPATIBILITY> -- Perl 5.005+ support, pure Perl
1891  
1892 =item * L</DIAGNOSTICS> -- Error messages
1893  
1894 =item * L</LIMITATIONS AND KNOWN ISSUES>
1895  
1896 =item * L</BUGS>
1897  
1898 =item * L</SEE ALSO>
1899  
1900 =back
1901  
1902 =head1 DESCRIPTION
1903  
1904 JSON::LINQ provides a LINQ-style query interface for JSON, JSONL
1905 (JSON Lines), and LTSV (Labeled Tab-Separated Values) files. It is
1906 the JSON counterpart of L<LTSV::LINQ>, sharing the same LINQ API and
1907 adding JSON-specific I/O methods.
1908  
1909 Key features:
1910  
1911 =over 4
1912  
1913 =item * B<Lazy evaluation> - O(1) memory for JSONL and LTSV streaming;
1914 JSON arrays are loaded once then iterated lazily
1915  
1916 =item * B<Method chaining> - Fluent, readable query composition
1917  
1918 =item * B<DSL syntax> - Simple key-value filtering
1919  
1920 =item * B<67 LINQ methods> - including JSON I/O (FromJSON, FromJSONL,
1921 FromJSONString, ToJSON, ToJSONL), LTSV I/O (FromLTSV, ToLTSV),
1922 CSV I/O (FromCSV, ToCSV), and all 60 methods from L<LTSV::LINQ>
1923  
1924 =item * B<Pure Perl> - No XS dependencies
1925  
1926 =item * B<Perl 5.005_03+> - Works on ancient and modern Perl
1927  
1928 =item * B<Built-in JSON parser> - No CPAN JSON module required
1929  
1930 =back
1931  
1932 =head2 Supported Data Sources
1933  
1934 =over 4
1935  
1936 =item * B<FromJSON($file)> - JSON file containing a top-level array or object
1937  
1938 =item * B<FromJSONL($file)> - JSONL file (one JSON value per line)
1939  
1940 =item * B<FromJSONString($json)> - JSON string (array or object)
1941  
1942 =item * B<FromLTSV($file)> - LTSV file (Labeled Tab-Separated Values)
1943  
1944 =item * B<FromCSV($file)> - CSV file (Comma-Separated Values; also TSV via sep option)
1945  
1946 =item * B<From(\@array)> - In-memory Perl array
1947  
1948 =item * B<Range($start, $count)> - Integer sequence
1949  
1950 =item * B<Empty()> - Empty sequence
1951  
1952 =item * B<Repeat($element, $count)> - Repeated element
1953  
1954 =back
1955  
1956 =head2 What is JSONL?
1957  
1958 JSONL (JSON Lines, also known as ndjson - newline-delimited JSON) is a
1959 text format where each line is a valid JSON value (typically an object).
1960 It is particularly suited for log files and streaming data because:
1961  
1962 =over 4
1963  
1964 =item * One record per line enables streaming with O(1) memory usage
1965  
1966 =item * Compatible with standard Unix tools (grep, sed, awk)
1967  
1968 =item * Easily appendable without rewriting the whole file
1969  
1970 =item * Each line is independently parseable
1971  
1972 =back
1973  
1974 B<Format example:>
1975  
1976 {"time":"2026-04-20T10:00:00","host":"192.0.2.1","status":200,"url":"/"}
1977 {"time":"2026-04-20T10:00:01","host":"192.0.2.2","status":404,"url":"/missing"}
1978  
1979 C<FromJSONL> reads these files lazily (one line at a time), matching the
1980 memory efficiency of C<LTSV::LINQ>'s C<FromLTSV>.
1981  
1982 =head2 What is LINQ?
1983  
1984 LINQ (Language Integrated Query) is the Microsoft .NET query API.
1985 This module brings the same LINQ interface to JSON data in Perl.
1986 See L<LTSV::LINQ> for a detailed description of the LINQ design philosophy.
1987  
1988 =head1 INCLUDED DOCUMENTATION
1989  
1990 The C<eg/> directory contains sample programs:
1991  
1992 eg/01_json_query.pl FromJSON/Where/Select/OrderByDescending/Distinct/ToLookup
1993 eg/02_jsonl_query.pl FromJSONL streaming, GroupBy, aggregation, ToJSONL
1994 eg/03_grouping.pl GroupBy, ToLookup, GroupJoin, SelectMany, Join
1995 eg/04_sorting.pl OrderBy/ThenBy multi-key sort, OrderByNum vs OrderByStr
1996 eg/05_json_ltsv_join.pl JOIN main JSON x sub-table LTSV
1997 eg/06_ltsv_json_join.pl JOIN main LTSV x sub-table JSON
1998 eg/07_csv_query.pl FromCSV/Where/Select/GroupBy/OrderByNum/ToCSV
1999 eg/08_csv_json_join.pl JOIN main CSV x sub-table JSON, CSV to JSON conversion
2000  
2001 The C<doc/> directory contains JSON::LINQ cheat sheets in 21 languages:
2002  
2003 doc/json_linq_cheatsheet.EN.txt English
2004 doc/json_linq_cheatsheet.JA.txt Japanese
2005 doc/json_linq_cheatsheet.ZH.txt Chinese (Simplified)
2006 doc/json_linq_cheatsheet.TW.txt Chinese (Traditional)
2007 doc/json_linq_cheatsheet.KO.txt Korean
2008 doc/json_linq_cheatsheet.FR.txt French
2009 doc/json_linq_cheatsheet.ID.txt Indonesian
2010 doc/json_linq_cheatsheet.VI.txt Vietnamese
2011 doc/json_linq_cheatsheet.TH.txt Thai
2012 doc/json_linq_cheatsheet.HI.txt Hindi
2013 doc/json_linq_cheatsheet.BN.txt Bengali
2014 doc/json_linq_cheatsheet.TR.txt Turkish
2015 doc/json_linq_cheatsheet.MY.txt Burmese
2016 doc/json_linq_cheatsheet.TL.txt Filipino
2017 doc/json_linq_cheatsheet.KM.txt Khmer
2018 doc/json_linq_cheatsheet.MN.txt Mongolian
2019 doc/json_linq_cheatsheet.NE.txt Nepali
2020 doc/json_linq_cheatsheet.SI.txt Sinhala
2021 doc/json_linq_cheatsheet.UR.txt Urdu
2022 doc/json_linq_cheatsheet.UZ.txt Uzbek
2023 doc/json_linq_cheatsheet.BM.txt Malay
2024  
2025 =head1 METHODS
2026  
2027 =head2 Complete Method Reference
2028  
2029 This module implements 67 LINQ methods organized into 15 categories.
2030 In addition, C<true> and C<false> boolean accessor functions are provided.
2031  
2032 =over 4
2033  
2034 =item * B<Data Sources (9)>: From, FromJSON, FromJSONL, FromJSONString, FromLTSV, FromCSV, Range, Empty, Repeat
2035  
2036 =item * B<Filtering (1)>: Where (with DSL)
2037  
2038 =item * B<Projection (2)>: Select, SelectMany
2039  
2040 =item * B<Concatenation (2)>: Concat, Zip
2041  
2042 =item * B<Partitioning (4)>: Take, Skip, TakeWhile, SkipWhile
2043  
2044 =item * B<Ordering (13)>: OrderBy, OrderByDescending, OrderByStr, OrderByStrDescending, OrderByNum, OrderByNumDescending, Reverse, ThenBy, ThenByDescending, ThenByStr, ThenByStrDescending, ThenByNum, ThenByNumDescending
2045  
2046 =item * B<Grouping (1)>: GroupBy
2047  
2048 =item * B<Set Operations (4)>: Distinct, Union, Intersect, Except
2049  
2050 =item * B<Join (2)>: Join, GroupJoin
2051  
2052 =item * B<Quantifiers (3)>: All, Any, Contains
2053  
2054 =item * B<Comparison (1)>: SequenceEqual
2055  
2056 =item * B<Element Access (8)>: First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault, ElementAt, ElementAtOrDefault
2057  
2058 =item * B<Aggregation (7)>: Count, Sum, Min, Max, Average, AverageOrDefault, Aggregate
2059  
2060 =item * B<Conversion (9)>: ToArray, ToList, ToDictionary, ToLookup, ToJSON, ToJSONL, ToLTSV, ToCSV, DefaultIfEmpty
2061  
2062 =item * B<Utility (1)>: ForEach
2063  
2064 =back
2065  
2066 =head2 JSON-Specific Data Source Methods
2067  
2068 =over 4
2069  
2070 =item B<FromJSON($filename)>
2071  
2072 Read a JSON file containing a top-level array of values. Each element of
2073 the array becomes one item in the sequence.
2074  
2075 my $q = JSON::LINQ->FromJSON("users.json");
2076  
2077 If the file contains a single JSON object (not an array), it is treated
2078 as a one-element sequence.
2079  
2080 B<File format:>
2081  
2082 [
2083 {"name": "Alice", "age": 30},
2084 {"name": "Bob", "age": 25}
2085 ]
2086  
2087 The entire file is read into memory and parsed once. For large files,
2088 consider JSONL format with C<FromJSONL> for streaming access.
2089  
2090 B<Concurrent use (e.g. Join/GroupJoin):> On Perl 5.006 and later,
2091 each call to C<FromJSON> uses a distinct numbered filehandle slot, so
2092 multiple iterators may be open simultaneously without interference.
2093 On Perl 5.005_03, a unique numbered package glob is used per call
2094 (JSON::LINQ::FH::H1, JSON::LINQ::FH::H2, ...) to achieve the same safety.
2095  
2096 =item B<FromJSONL($filename)>
2097  
2098 Read a JSONL (JSON Lines) file. Each non-empty line is parsed as a
2099 separate JSON value. Empty lines and lines starting with C<#> are skipped.
2100  
2101 my $q = JSON::LINQ->FromJSONL("events.jsonl");
2102  
2103 B<File format:>
2104  
2105 {"event":"login","user":"alice","ts":1713600000}
2106 {"event":"purchase","user":"alice","ts":1713600060,"amount":29.99}
2107 {"event":"logout","user":"alice","ts":1713600120}
2108  
2109 C<FromJSONL> reads lazily (one line at a time), providing O(1) memory
2110 usage for arbitrarily large files.
2111  
2112 Invalid JSON lines produce a warning and are skipped rather than
2113 aborting the entire sequence.
2114  
2115 B<Concurrent use (e.g. Join/GroupJoin):> On Perl 5.006 and later,
2116 each call to C<FromJSONL> uses a distinct numbered filehandle slot, so
2117 multiple iterators may be open simultaneously without interference.
2118 On Perl 5.005_03, a unique numbered package glob is used per call
2119 (JSON::LINQ::FH::H1, JSON::LINQ::FH::H2, ...) to achieve the same safety.
2120  
2121 =item B<FromJSONString($json)>
2122  
2123 Create a query from a JSON string. Accepts a JSON array (each element
2124 becomes one sequence item) or a JSON object (single-element sequence).
2125  
2126 my $q = JSON::LINQ->FromJSONString('[{"id":1},{"id":2}]');
2127 my $q = JSON::LINQ->FromJSONString('{"id":1,"name":"Alice"}');
2128  
2129 =back
2130  
2131 =head2 LTSV Interoperability
2132  
2133 To make it easy to JOIN JSON data with LTSV master/lookup tables (or vice
2134 versa) without requiring L<LTSV::LINQ> to be installed, JSON::LINQ ships
2135 with built-in LTSV I/O methods. The LTSV format is described at
2136 L<http://ltsv.org/>.
2137  
2138 =over 4
2139  
2140 =item B<FromLTSV($filename)>
2141  
2142 Read an LTSV (Labeled Tab-Separated Values) file. Each line is split on
2143 TAB, and each field is split on the first colon to produce a label/value
2144 pair. The result is a sequence of hash references.
2145  
2146 my $q = JSON::LINQ->FromLTSV("departments.ltsv");
2147  
2148 B<File format:>
2149  
2150 id:1<TAB>name:Engineering<TAB>head:Alice
2151 id:2<TAB>name:Sales<TAB>head:Bob
2152  
2153 C<FromLTSV> reads lazily (one line at a time), so memory usage is O(1)
2154 even for very large files. Empty lines are skipped. CR is stripped to
2155 handle CRLF files on any platform.
2156  
2157 B<Concurrent use (e.g. Join/GroupJoin):> On Perl 5.006 and later,
2158 each call to C<FromLTSV> uses a distinct numbered filehandle slot, so
2159 multiple iterators may be open simultaneously without interference.
2160 On Perl 5.005_03, a unique numbered package glob is used per call
2161 (JSON::LINQ::FH::H1, JSON::LINQ::FH::H2, ...) to achieve the same safety.
2162  
2163 =item B<ToLTSV($filename)>
2164  
2165 =item B<ToLTSV($filename, label_order =E<gt> \@labels)>
2166  
2167 =item B<ToLTSV($filename, headers =E<gt> \@labels)>
2168  
2169 Write the sequence as an LTSV file. Each element must be a HASH reference.
2170 TAB, CR, and LF in values are sanitized to a single space to keep the file
2171 structurally valid.
2172  
2173 $query->ToLTSV("output.ltsv");
2174  
2175 B<Output format (default - all keys, alphabetical):>
2176  
2177 age:30<TAB>name:Alice
2178 age:25<TAB>name:Bob
2179  
2180 B<label_order> (or its alias B<headers>) specifies which labels to emit and
2181 in what order. Labels not present in a record are silently skipped.
2182  
2183 $query->ToLTSV("output.ltsv", label_order => [qw(name age)]);
2184 $query->ToLTSV("output.ltsv", headers => [qw(name age)]);
2185  
2186 B<Output format (with label_order):>
2187  
2188 name:Alice<TAB>age:30
2189 name:Bob<TAB>age:25
2190  
2191 =back
2192  
2193 =head2 CSV Interoperability
2194  
2195 CSV (Comma-Separated Values) is the most widely used format for tabular
2196 data exchange. C<FromCSV> and C<ToCSV> let a JSON::LINQ pipeline read
2197 from and write to CSV files without requiring any extra CPAN module.
2198  
2199 The separator character defaults to C<','> but can be set to C<"\t"> to
2200 handle TSV (Tab-Separated Values) files, or any other single character.
2201  
2202 =over 4
2203  
2204 =item B<FromCSV($filename)>
2205  
2206 =item B<FromCSV($filename, sep =E<gt> $char)>
2207  
2208 =item B<FromCSV($filename, headers =E<gt> \@cols)>
2209  
2210 =item B<FromCSV($filename, headers =E<gt> \@cols, skip_header =E<gt> 1)>
2211  
2212 Read a CSV file. The first line is used as the header row (column names),
2213 and each subsequent data row is returned as a hash reference with those
2214 column names as keys.
2215  
2216 B<Options:>
2217  
2218 =over 4
2219  
2220 =item C<sep> - Field separator character (default: C<','>). Use C<"\t"> for TSV.
2221  
2222 =item C<headers> - Array reference of column names. When given, the first
2223 data line is treated as data rather than a header. Combine with
2224 C<skip_header =E<gt> 1> to skip an existing header row in the file.
2225  
2226 =item C<skip_header> - If true, skip the first line of the file even when
2227 C<headers> is given.
2228  
2229 =back
2230  
2231 # Standard CSV with header row
2232 my $q = JSON::LINQ->FromCSV("data.csv");
2233  
2234 # Tab-separated (TSV)
2235 my $q = JSON::LINQ->FromCSV("data.tsv", sep => "\t");
2236  
2237 # Headerless CSV with explicit column names
2238 my $q = JSON::LINQ->FromCSV("noheader.csv",
2239 headers => [qw(name age city)]);
2240  
2241 C<FromCSV> reads the file lazily (one line at a time), providing O(1)
2242 memory usage for arbitrarily large files.
2243  
2244 B<RFC 4180 compliance:> Quoted fields (including fields containing
2245 the separator, double-quotes escaped as C<"">, or newline characters)
2246 are handled correctly. See L</LIMITATIONS AND KNOWN ISSUES> for the
2247 one known exception (multi-line quoted fields).
2248  
2249 B<Concurrent use (e.g. Join/GroupJoin):> Each call to C<FromCSV> uses a
2250 unique numbered package glob (JSON::LINQ::FH::H1, H2, ...) on all Perl
2251 versions, so multiple CSV iterators may be open simultaneously without
2252 interference.
2253  
2254 =item B<ToCSV($filename)>
2255  
2256 =item B<ToCSV($filename, sep =E<gt> $char)>
2257  
2258 =item B<ToCSV($filename, headers =E<gt> \@cols)>
2259  
2260 =item B<ToCSV($filename, label_order =E<gt> \@cols)>
2261  
2262 =item B<ToCSV($filename, no_header =E<gt> 1)>
2263  
2264 Write the sequence as a CSV file.
2265  
2266 B<Options:>
2267  
2268 =over 4
2269  
2270 =item C<sep> - Field separator character (default: C<','>).
2271  
2272 =item C<headers> - Array reference of column names that controls which keys
2273 are written and in what order. Also serves as the header row.
2274  
2275 =item C<label_order> - Alias for C<headers>.
2276  
2277 =item C<no_header> - If true, suppress the header row entirely.
2278  
2279 =back
2280  
2281 $query->ToCSV("output.csv");
2282 $query->ToCSV("output.tsv", sep => "\t");
2283 $query->ToCSV("output.csv", headers => [qw(name age city)]);
2284  
2285 When C<headers>/C<label_order> is not supplied and elements are HASH
2286 references, column names are taken from the first record's keys in
2287 alphabetical order.
2288  
2289 =back
2290  
2291 =head2 JSON-Specific Conversion Methods
2292  
2293 =over 4
2294  
2295 =item B<ToJSON($filename)>
2296  
2297 Write the sequence as a JSON file containing a JSON array. Each element
2298 is encoded as JSON. The output is a valid JSON array.
2299  
2300 $query->ToJSON("output.json");
2301  
2302 B<Output format:>
2303  
2304 [
2305 {"age":30,"name":"Alice"},
2306 {"age":25,"name":"Bob"}
2307 ]
2308  
2309 Hash keys are sorted alphabetically for deterministic output.
2310  
2311 =item B<ToJSONL($filename)>
2312  
2313 Write the sequence as a JSONL file. Each element is written as one line
2314 of JSON. This is the streaming counterpart of C<ToJSON>.
2315  
2316 $query->ToJSONL("output.jsonl");
2317  
2318 B<Output format:>
2319  
2320 {"age":30,"name":"Alice"}
2321 {"age":25,"name":"Bob"}
2322  
2323 =back
2324  
2325 =head2 Boolean Values
2326  
2327 JSON::LINQ provides boolean singleton objects compatible with JSON encoding:
2328  
2329 JSON::LINQ::true # stringifies as "true", numifies as 1
2330 JSON::LINQ::false # stringifies as "false", numifies as 0
2331  
2332 Use these when creating data structures that will be serialised to JSON:
2333  
2334 my $rec = { active => JSON::LINQ::true, count => 0 };
2335 # ToJSON encodes as: {"active":true,"count":0}
2336  
2337 When C<FromJSON> or C<FromJSONL> decode a JSON C<true> or C<false>,
2338 the result is a C<JSON::LINQ::Boolean> object that behaves as 1 or 0
2339 in numeric and boolean context.
2340  
2341 =head2 All Other Methods
2342  
2343 All other LINQ methods are inherited from L<LTSV::LINQ> and behave
2344 identically. Please refer to L<LTSV::LINQ> for complete documentation of:
2345  
2346 Where, Select, SelectMany, Concat, Zip, Take, Skip, TakeWhile,
2347 SkipWhile, OrderBy, OrderByDescending, OrderByStr, OrderByStrDescending,
2348 OrderByNum, OrderByNumDescending, Reverse, ThenBy, ThenByDescending,
2349 ThenByStr, ThenByStrDescending, ThenByNum, ThenByNumDescending, GroupBy,
2350 Distinct, Union, Intersect, Except, Join, GroupJoin, All, Any, Contains,
2351 SequenceEqual, First, FirstOrDefault, Last, LastOrDefault, Single,
2352 SingleOrDefault, ElementAt, ElementAtOrDefault, Count, Sum, Min, Max,
2353 Average, AverageOrDefault, Aggregate, ToArray, ToList, ToDictionary,
2354 ToLookup, DefaultIfEmpty, ForEach.
2355  
2356 =head1 EXAMPLES
2357  
2358 =head2 Basic JSON File Query
2359  
2360 use JSON::LINQ;
2361  
2362 # users.json: [{"name":"Alice","age":30}, {"name":"Bob","age":25}, ...]
2363 my @adults = JSON::LINQ->FromJSON("users.json")
2364 ->Where(sub { $_[0]{age} >= 18 })
2365 ->OrderBy(sub { $_[0]{name} })
2366 ->ToArray();
2367  
2368 =head2 JSONL Streaming
2369  
2370 # events.jsonl: one JSON object per line
2371 my $error_count = JSON::LINQ->FromJSONL("events.jsonl")
2372 ->Count(sub { $_[0]{level} eq 'ERROR' });
2373  
2374 JSON::LINQ->FromJSONL("events.jsonl")
2375 ->Where(sub { $_[0]{level} eq 'ERROR' })
2376 ->ForEach(sub { print $_[0]{message}, "\n" });
2377  
2378 =head2 Aggregation
2379  
2380 my $avg = JSON::LINQ->FromJSON("orders.json")
2381 ->Where(sub { $_[0]{status} eq 'completed' })
2382 ->Average(sub { $_[0]{amount} });
2383  
2384 printf "Average order: %.2f\n", $avg;
2385  
2386 =head2 Grouping
2387  
2388 my @by_category = JSON::LINQ->FromJSON("products.json")
2389 ->GroupBy(sub { $_[0]{category} })
2390 ->Select(sub {
2391 my $g = shift;
2392 {
2393 Category => $g->{Key},
2394 Count => scalar(@{$g->{Elements}}),
2395 MaxPrice => JSON::LINQ->From($g->{Elements})
2396 ->Max(sub { $_[0]{price} }),
2397 }
2398 })
2399 ->OrderByDescending(sub { $_[0]{Count} })
2400 ->ToArray();
2401  
2402 =head2 Transform and Write
2403  
2404 # Read JSON, transform, write back as JSONL
2405 JSON::LINQ->FromJSON("input.json")
2406 ->Select(sub {
2407 my $r = shift;
2408 return { %$r, processed => JSON::LINQ::true };
2409 })
2410 ->ToJSONL("output.jsonl");
2411  
2412 =head2 JOIN: JSON (main) with LTSV (sub-table)
2413  
2414 A common pattern: the primary records live in a JSON file, and a small
2415 lookup table is maintained in LTSV format. The example below reads
2416 employees from a JSON file and joins them against a department lookup
2417 table in LTSV format.
2418  
2419 # employees.json
2420 # [
2421 # {"id":1,"name":"Alice","dept_id":10},
2422 # {"id":2,"name":"Bob", "dept_id":20},
2423 # {"id":3,"name":"Carol","dept_id":10}
2424 # ]
2425 #
2426 # departments.ltsv
2427 # id:10<TAB>name:Engineering
2428 # id:20<TAB>name:Sales
2429  
2430 my $depts = JSON::LINQ->FromLTSV("departments.ltsv");
2431  
2432 my @joined = JSON::LINQ->FromJSON("employees.json")
2433 ->Join($depts,
2434 sub { $_[0]{dept_id} }, # outer key (JSON side)
2435 sub { $_[0]{id} }, # inner key (LTSV side)
2436 sub { { name => $_[0]{name},
2437 dept => $_[1]{name} } })
2438 ->OrderBy(sub { $_[0]{name} })
2439 ->ToArray();
2440  
2441 # @joined == ({name=>"Alice", dept=>"Engineering"},
2442 # {name=>"Bob", dept=>"Sales"},
2443 # {name=>"Carol", dept=>"Engineering"})
2444  
2445 =head2 JOIN: LTSV (main) with JSON (sub-table)
2446  
2447 The opposite pattern: the primary records are in an LTSV log file (often
2448 high-volume, append-only), and the lookup table is in JSON.
2449  
2450 # orders.ltsv
2451 # id:1001<TAB>sku:A100<TAB>qty:2
2452 # id:1002<TAB>sku:B200<TAB>qty:1
2453 # id:1003<TAB>sku:A100<TAB>qty:5
2454 #
2455 # prices.json
2456 # [
2457 # {"sku":"A100","price":300},
2458 # {"sku":"B200","price":1200}
2459 # ]
2460  
2461 my $prices = JSON::LINQ->FromJSON("prices.json");
2462  
2463 my @priced = JSON::LINQ->FromLTSV("orders.ltsv")
2464 ->Join($prices,
2465 sub { $_[0]{sku} }, # outer key (LTSV)
2466 sub { $_[0]{sku} }, # inner key (JSON)
2467 sub { { order_id => $_[0]{id},
2468 amount => $_[0]{qty} * $_[1]{price} } })
2469 ->ToArray();
2470  
2471 # @priced == ({order_id=>1001, amount=>600},
2472 # {order_id=>1002, amount=>1200},
2473 # {order_id=>1003, amount=>1500})
2474  
2475 C<Join> builds a hash from the inner (sub-table) sequence, so it is
2476 efficient even when the outer sequence is large and read lazily.
2477  
2478 C<Join> builds a hash from the inner (sub-table) sequence, so it is
2479 efficient even when the outer sequence is large and read lazily.
2480  
2481 =head2 Basic CSV Query
2482  
2483 use JSON::LINQ;
2484  
2485 # sales.csv:
2486 # name,amount,category
2487 # Alice,1500,A
2488 # Bob,800,B
2489 # Carol,2000,A
2490  
2491 my @high_sales = JSON::LINQ->FromCSV("sales.csv")
2492 ->Where(sub { $_[0]{amount} > 1000 })
2493 ->OrderByNumDescending(sub { $_[0]{amount} })
2494 ->ToArray();
2495  
2496 =head2 DSL Filtering on CSV
2497  
2498 my @tokyo = JSON::LINQ->FromCSV("users.csv")
2499 ->Where(city => 'Tokyo')
2500 ->ToArray();
2501  
2502 =head2 Grouping and Aggregation on CSV
2503  
2504 my @by_category = JSON::LINQ->FromCSV("sales.csv")
2505 ->GroupBy(sub { $_[0]{category} })
2506 ->Select(sub {
2507 my $g = shift;
2508 {
2509 Category => $g->{Key},
2510 Count => scalar(@{$g->{Elements}}),
2511 Total => JSON::LINQ->From($g->{Elements})
2512 ->Sum(sub { $_[0]{amount} }),
2513 }
2514 })
2515 ->OrderByStrDescending(sub { $_[0]{Total} })
2516 ->ToArray();
2517  
2518 =head2 JOIN Two CSV Files
2519  
2520 # orders.csv: id,customer_id,amount
2521 # customers.csv: id,name,city
2522  
2523 my $orders = JSON::LINQ->FromCSV("orders.csv");
2524 my $customers = JSON::LINQ->FromCSV("customers.csv");
2525  
2526 my @joined = $orders->Join(
2527 $customers,
2528 sub { $_[0]{customer_id} },
2529 sub { $_[0]{id} },
2530 sub { { Name => $_[1]{name}, Amount => $_[0]{amount} } }
2531 )->ToArray();
2532  
2533 =head2 TSV Support
2534  
2535 my @data = JSON::LINQ->FromCSV("data.tsv", sep => "\t")
2536 ->Where(status => 'active')
2537 ->ToArray();
2538  
2539 =head2 CSV Round-Trip (Filter and Write)
2540  
2541 JSON::LINQ->FromCSV("input.csv")
2542 ->Where(sub { $_[0]{active} eq '1' })
2543 ->ToCSV("active.csv");
2544  
2545 =head2 CSV to JSON Conversion
2546  
2547 JSON::LINQ->FromCSV("data.csv")
2548 ->Select(sub {
2549 my $r = shift;
2550 return { %$r, processed => JSON::LINQ::true };
2551 })
2552 ->ToJSON("data.json");
2553  
2554 =head2 In-Memory Array Query
2555  
2556 my @data = (
2557 {name => 'Alice', score => 95},
2558 {name => 'Bob', score => 72},
2559 {name => 'Carol', score => 88},
2560 );
2561  
2562 my @top = JSON::LINQ->From(\@data)
2563 ->Where(sub { $_[0]{score} >= 80 })
2564 ->OrderByDescending(sub { $_[0]{score} })
2565 ->ToArray();
2566  
2567 =head1 FEATURES
2568  
2569 =head2 Lazy Evaluation
2570  
2571 C<FromJSONL> reads one line at a time. Combined with C<Where> and C<Take>,
2572 only the needed records are ever in memory simultaneously.
2573  
2574 C<FromJSON> reads the whole file once but then iterates the array lazily.
2575  
2576 =head2 Built-in JSON Parser
2577  
2578 JSON::LINQ contains its own JSON encoder/decoder (derived from mb::JSON 0.06).
2579 No CPAN JSON module is required. The parser handles:
2580  
2581 =over 4
2582  
2583 =item * UTF-8 multibyte strings (output as-is, not \uXXXX-escaped)
2584  
2585 =item * C<\uXXXX> escape sequences on input (converted to UTF-8)
2586  
2587 =item * All JSON types: object, array, string, number, true, false, null
2588  
2589 =item * Nested structures of arbitrary depth
2590  
2591 =back
2592  
2593 =head1 ARCHITECTURE
2594  
2595 =head2 Relationship to LTSV::LINQ
2596  
2597 JSON::LINQ and LTSV::LINQ are parallel modules sharing the same LINQ API.
2598  
2599 LTSV::LINQ - LINQ for LTSV (Labeled Tab-Separated Values) files
2600 JSON::LINQ - LINQ for JSON and JSONL files
2601  
2602 Both share the same LINQ API. JSON::LINQ adds the following I/O methods
2603 on top of LTSV::LINQ's interface:
2604  
2605 FromJSON($file) - read JSON array file
2606 FromJSONL($file) - read JSONL file (streaming)
2607 FromJSONString($json) - read JSON string
2608 FromLTSV($file) - read LTSV file (streaming)
2609 FromCSV($file) - read CSV file (streaming, RFC 4180)
2610 ToJSON($file) - write JSON array file
2611 ToJSONL($file) - write JSONL file
2612 ToLTSV($file) - write LTSV file (streaming)
2613 ToCSV($file) - write CSV file
2614  
2615 C<FromLTSV>, C<ToLTSV>, C<FromCSV>, and C<ToCSV> are provided so a
2616 JSON::LINQ pipeline can JOIN against (or emit into) LTSV and CSV files
2617 without requiring LTSV::LINQ or CSV::LINQ to be installed.
2618  
2619 The internal iterator architecture is identical: each operator returns a
2620 new query object wrapping a closure.
2621  
2622 =head2 Memory Characteristics
2623  
2624 FromJSONL - O(1) per record: one line at a time
2625 FromJSON - O(n): entire file loaded once, then lazy iteration
2626 FromLTSV - O(1) per record: one line at a time
2627 FromCSV - O(1) per record: one line at a time
2628 ToJSON - O(n): entire sequence collected for array output
2629 ToJSONL - O(1) per record: streaming write
2630 ToLTSV - O(1) per record: streaming write
2631 ToCSV - O(n): entire sequence collected before writing header
2632  
2633 =head1 COMPATIBILITY
2634  
2635 =head2 Perl Version Support
2636  
2637 Compatible with B<Perl 5.00503 and later>. See L<LTSV::LINQ> for the
2638 full compatibility rationale (Universal Consensus 1998 / Perl 5.005_03).
2639  
2640 =head2 Pure Perl Implementation
2641  
2642 No XS dependencies. No CPAN module dependencies. Works on any Perl
2643 installation with only the standard core.
2644  
2645 =head2 JSON Limitations
2646  
2647 The built-in parser has the same limitations as mb::JSON 0.06:
2648  
2649 =over 4
2650  
2651 =item * Surrogate pairs (C<\uD800>-C<\uDFFF>) are not supported
2652  
2653 =item * Circular references in encoding cause infinite recursion
2654  
2655 =item * Non-ARRAY/HASH references are stringified
2656  
2657 =back
2658  
2659 =head2 Iterator Protocol and JSON null
2660  
2661 The internal iterator protocol uses C<undef> to signal end-of-sequence.
2662 As a consequence, an C<undef> value (i.e. a decoded JSON C<null>) cannot
2663 appear as a I<top-level element> of a sequence: it would be
2664 indistinguishable from EOF and the sequence would be silently truncated
2665 at that point.
2666  
2667 This affects C<Select> in particular: a selector that returns C<undef>
2668 for some elements will terminate the sequence early.
2669  
2670 # JSON: [{"v":1},{"v":null},{"v":3}]
2671 JSON::LINQ->FromJSON("data.json")
2672 ->Select(sub { $_[0]{v} })
2673 ->ToArray;
2674 # returns (1) - sequence stops at the undef from the second record
2675  
2676 C<Where> is unaffected when filtering hash records (the hashref itself
2677 is the element, not its C<v> field), but a C<Select> that projects a
2678 nullable field will be truncated at the first C<null>. Workarounds:
2679  
2680 =over 4
2681  
2682 =item * Project to a sentinel value: C<< Select(sub { defined $_[0]{v} ? $_[0]{v} : '' }) >>
2683  
2684 =item * Wrap each element in a hashref so the element itself is never undef.
2685  
2686 =back
2687  
2688 C<DefaultIfEmpty(undef)> is similarly affected: a default of C<undef>
2689 is silently lost. Use a non-undef sentinel (C<0>, C<''>, C<{}>) instead.
2690  
2691 =head1 DIAGNOSTICS
2692  
2693 =over 4
2694  
2695 =item C<JSON::LINQ::FromJSON: cannot parse '$file': $@>
2696  
2697 The file exists but does not contain valid JSON.
2698  
2699 =item C<JSON::LINQ::FromJSON: '$file' must contain a JSON array or object>
2700  
2701 The file contains valid JSON but the top-level value is a string, number,
2702 or boolean, not an array or object.
2703  
2704 =item C<JSON::LINQ::FromJSONL: skipping invalid JSON line: $@>
2705  
2706 A line in a JSONL file could not be parsed. The line is skipped with a
2707 warning; processing continues.
2708  
2709 =item C<JSON::LINQ::FromJSONString: cannot parse JSON: $@>
2710  
2711 The supplied JSON string is not valid JSON.
2712  
2713 =item C<JSON::LINQ::_json_decode: ...>
2714  
2715 Internal JSON parsing error. The message includes the specific unexpected
2716 token or an indication of where parsing stopped.
2717  
2718 =item C<JSON::LINQ::_json_decode: expected ',' or ']' in array>
2719  
2720 The JSON array was not properly terminated or separated.
2721  
2722 =item C<JSON::LINQ::_json_decode: expected ',' or '}' in object>
2723  
2724 A JSON object was not properly terminated or separated.
2725  
2726 =item C<JSON::LINQ::_json_decode: expected ':' after key '$key'>
2727  
2728 The colon separator was missing after a JSON object key.
2729  
2730 =item C<JSON::LINQ::_json_decode: expected string key in object>
2731  
2732 A JSON object key was not a quoted string.
2733  
2734 =item C<JSON::LINQ::_json_decode: trailing garbage: >
2735  
2736 Extra text was found after a successfully parsed top-level JSON value.
2737 The message is followed by the first 20 characters of the unexpected text.
2738  
2739 =item C<JSON::LINQ::_json_decode: unexpected end of input>
2740  
2741 The JSON text ended before a complete value was parsed.
2742  
2743 =item C<JSON::LINQ::_json_decode: unexpected token: >
2744  
2745 An unrecognised token was encountered while parsing JSON.
2746 The message is followed by the first 20 characters of the unexpected text.
2747  
2748 =item C<JSON::LINQ::_json_decode: unterminated string>
2749  
2750 A JSON string was not closed with a double-quote.
2751  
2752 =item C<Cannot open '$file': $!>
2753  
2754 Thrown by C<FromJSON>, C<FromJSONL>, C<FromLTSV>, or C<FromCSV> when the input file
2755 cannot be opened.
2756  
2757 =item C<Cannot open '$filename': $!>
2758  
2759 Thrown by C<ToJSON>, C<ToJSONL>, C<ToLTSV>, or C<ToCSV> when the output file
2760 cannot be opened.
2761  
2762 =item C<From() requires ARRAY reference>
2763  
2764 Thrown by C<From()> when the argument is not an array reference.
2765  
2766 =item C<Index must be non-negative>
2767  
2768 Thrown by C<ElementAt()> when the supplied index is less than zero.
2769  
2770 =item C<Index out of range>
2771  
2772 Thrown by C<ElementAt()> when the index is beyond the end of the sequence.
2773 Use C<ElementAtOrDefault()> to avoid this error.
2774  
2775 =item C<Invalid number of arguments for Aggregate>
2776  
2777 Thrown by C<Aggregate()> when called with an argument count other than 1, 2, or 3.
2778  
2779 =item C<Sequence contains no elements>
2780  
2781 Thrown by C<First()>, C<Last()>, C<Average()>, C<Aggregate()> (no-seed form), and
2782 C<Single()> when the sequence is empty or no element satisfies the predicate.
2783  
2784 =item C<Sequence contains more than one element>
2785  
2786 Thrown by C<Single()> when more than one element (or matching element) is found.
2787  
2788 =item C<No element satisfies the condition>
2789  
2790 Thrown by C<First()> or C<Last()> with a predicate when no element matches.
2791  
2792 =item C<SelectMany: selector must return an ARRAY reference>
2793  
2794 Thrown by C<SelectMany()> when the selector function returns a non-array value.
2795  
2796 =back
2797  
2798 All other error messages are identical to L<LTSV::LINQ>.
2799  
2800 =head1 LIMITATIONS AND KNOWN ISSUES
2801  
2802 =over 4
2803  
2804 =item * B<Iterator Consumption>
2805  
2806 Query objects can only be consumed once. The iterator is exhausted after
2807 terminal operations (C<ToArray>, C<Count>, C<Sum>, C<ToCSV>, etc.).
2808 Create a new query or save the C<ToArray()> result to reuse data.
2809  
2810 =item * B<Undef Values>
2811  
2812 Due to the iterator-based design, C<undef> signals end-of-sequence.
2813 A C<Select> selector that returns C<undef> will terminate the sequence
2814 early. See L</Iterator Protocol and JSON null> for details and workarounds.
2815  
2816 =item * B<Multi-line CSV Fields>
2817  
2818 C<FromCSV> reads the file one line at a time. RFC 4180 quoted fields
2819 that contain embedded newlines (multi-line fields) are not yet
2820 supported. Single-line quoted fields containing commas and escaped
2821 double-quotes (C<"">) are handled correctly.
2822  
2823 =item * B<No Parallel Execution>
2824  
2825 All operations execute sequentially in a single thread.
2826  
2827 =back
2828  
2829 =head1 BUGS
2830  
2831 Please report bugs to C<ina@cpan.org>.
2832  
2833 =head1 SEE ALSO
2834  
2835 =over 4
2836  
2837 =item * L<LTSV::LINQ> - The LTSV counterpart of this module
2838  
2839 =item * L<CSV::LINQ> - LINQ-style query interface for CSV files
2840  
2841 =item * L<mb::JSON> - The JSON encoder/decoder this module's parser is derived from
2842  
2843 =item * JSONL specification: L<https://jsonlines.org/>
2844  
2845 =item * RFC 4180 (CSV): L<https://www.ietf.org/rfc/rfc4180.txt>
2846  
2847 =item * Microsoft LINQ documentation: L<https://learn.microsoft.com/en-us/dotnet/csharp/linq/>
2848  
2849 =back
2850  
2851 =head1 AUTHOR
2852  
2853 INABA Hitoshi E<lt>ina@cpan.orgE<gt>
2854  
2855 =head1 COPYRIGHT AND LICENSE
2856  
2857 Copyright (c) 2026 INABA Hitoshi
2858  
2859 This library is free software; you can redistribute it and/or modify
2860 it under the same terms as Perl itself.
2861  
2862 =head1 DISCLAIMER OF WARRANTY
2863  
2864 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
2865 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
2866 WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
2867 PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
2868 EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2869 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
2870 THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS
2871 WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF
2872 ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
2873  
2874 =cut
↑ Summary