line |
stmt |
bran |
cond |
sub |
pod |
time |
code |
1
|
|
|
|
|
|
|
package List::Categorize::Multi; |
2
|
3
|
|
|
3
|
|
129131
|
use strict; |
|
3
|
|
|
|
|
10
|
|
|
3
|
|
|
|
|
110
|
|
3
|
3
|
|
|
3
|
|
17
|
use warnings; |
|
3
|
|
|
|
|
7
|
|
|
3
|
|
|
|
|
109
|
|
4
|
|
|
|
|
|
|
|
5
|
3
|
|
|
3
|
|
20
|
use Exporter qw/import/; |
|
3
|
|
|
|
|
10
|
|
|
3
|
|
|
|
|
99
|
|
6
|
3
|
|
|
3
|
|
15
|
use Carp qw/croak/; |
|
3
|
|
|
|
|
7
|
|
|
3
|
|
|
|
|
1009
|
|
7
|
|
|
|
|
|
|
|
8
|
|
|
|
|
|
|
our $VERSION = '0.02'; |
9
|
|
|
|
|
|
|
our @EXPORT = qw(categorize); |
10
|
|
|
|
|
|
|
|
11
|
|
|
|
|
|
|
sub categorize (&@) { |
12
|
16
|
|
|
16
|
1
|
172492
|
my $coderef = shift; # the rest of @_ is the list of elements to categorize |
13
|
|
|
|
|
|
|
|
14
|
16
|
|
|
|
|
38
|
my %tree = (); |
15
|
|
|
|
|
|
|
|
16
|
16
|
|
|
|
|
69
|
for my $element (@_) { |
17
|
|
|
|
|
|
|
# localize $_ and call the coderef |
18
|
197
|
|
|
|
|
291
|
local $_ = $element; |
19
|
197
|
|
|
|
|
381
|
my @categories = $coderef->(); # expected: list of categorizing scalars |
20
|
|
|
|
|
|
|
|
21
|
|
|
|
|
|
|
# loop over categories, using them to walk through/create the tree |
22
|
197
|
|
|
|
|
1383
|
my $node = \%tree; |
23
|
|
|
|
|
|
|
CATEGORY: |
24
|
197
|
|
|
|
|
437
|
while (@categories) { |
25
|
185
|
|
|
|
|
236
|
my $categ = shift @categories; |
26
|
|
|
|
|
|
|
|
27
|
|
|
|
|
|
|
# if an undef is encountered, this element will be ignored |
28
|
185
|
100
|
|
|
|
381
|
defined $categ or last; |
29
|
|
|
|
|
|
|
|
30
|
183
|
100
|
|
|
|
357
|
if (@categories) { |
31
|
|
|
|
|
|
|
# create or retrieve an intermediate node |
32
|
15
|
|
100
|
|
|
47
|
$node = $node->{$categ} ||= {}; |
33
|
15
|
100
|
|
|
|
255
|
ref $node ne 'ARRAY' |
34
|
|
|
|
|
|
|
or croak "inconsistent use of category '$categ'"; |
35
|
|
|
|
|
|
|
} |
36
|
|
|
|
|
|
|
else { |
37
|
|
|
|
|
|
|
# add the element to a leaf |
38
|
168
|
|
100
|
|
|
530
|
my $ref = ref $node->{$categ} || ''; |
39
|
168
|
50
|
|
|
|
328
|
$ref ne 'HASH' |
40
|
|
|
|
|
|
|
or croak "inconsistent use of category '$categ'"; |
41
|
168
|
|
|
|
|
157
|
push @{$node->{$categ}}, $_; |
|
168
|
|
|
|
|
767
|
|
42
|
|
|
|
|
|
|
} |
43
|
|
|
|
|
|
|
} |
44
|
|
|
|
|
|
|
} |
45
|
|
|
|
|
|
|
|
46
|
15
|
|
|
|
|
98
|
return %tree; |
47
|
|
|
|
|
|
|
} |
48
|
|
|
|
|
|
|
|
49
|
|
|
|
|
|
|
1; |
50
|
|
|
|
|
|
|
|
51
|
|
|
|
|
|
|
__END__ |