File Coverage

blib/lib/List/Haystack.pm
Criterion Covered Total %
statement 36 36 100.0
branch 10 10 100.0
condition 4 5 80.0
subroutine 9 9 100.0
pod 4 4 100.0
total 63 64 98.4


line stmt bran cond sub pod time code
1             package List::Haystack;
2 4     4   4164 use 5.008001;
  4         19  
3 4     4   26 use strict;
  4         10  
  4         93  
4 4     4   23 use warnings;
  4         12  
  4         128  
5 4     4   26 use Carp qw/croak/;
  4         15  
  4         1578  
6              
7             our $VERSION = "0.01";
8              
9             sub new {
10 16     16 1 44907 my ($class, $list, $options) = @_;
11              
12 16 100       67 if (not defined $list) {
13 3         10 $list = [];
14             }
15              
16 16 100       66 if (ref $list ne 'ARRAY') {
17 1         133 croak 'Type of given argument `$list` is not suitable. It must be array reference.';
18             }
19              
20 15         61 my $self = bless {
21             list => $list,
22             }, $class;
23              
24 15   66     141 my $lazy = defined $options && ref($options) eq 'HASH' && $options->{lazy};
25 15 100       59 if (not $lazy) {
26 8         30 $self->_construct_haystack;
27             }
28              
29 15         60 return $self;
30             }
31              
32             sub haystack {
33 16     16 1 41 my ($self) = @_;
34              
35 16         40 my $haystack = $self->{haystack};
36 16 100       62 if (defined $haystack) {
37 12         110 return $haystack;
38             }
39              
40             # For lazy building
41 4         18 return $self->_construct_haystack;
42             }
43              
44             sub find {
45 8     8 1 2456 my ($self, $needle) = @_;
46              
47 8 100       34 return exists($self->haystack->{$needle}) ? 1 : 0;
48             }
49              
50             sub cnt {
51 8     8 1 1729 my ($self, $needle) = @_;
52              
53 8   100     20 return $self->haystack->{$needle} || 0;
54             }
55              
56             sub _construct_haystack {
57 12     12   221 my ($self) = @_;
58              
59 12         34 my %haystack;
60 12         27 for my $item (@{($self->{list})}) {
  12         54  
61 15         41 $haystack{$item}++;
62             }
63              
64 12         70 $self->{haystack} = \%haystack;
65             }
66              
67             1;
68             __END__