File Coverage

blib/lib/Iterator/ToArray.pm
Criterion Covered Total %
statement 36 37 97.3
branch 5 6 83.3
condition 6 12 50.0
subroutine 10 10 100.0
pod 0 3 0.0
total 57 68 83.8


line stmt bran cond sub pod time code
1             package Iterator::ToArray;
2              
3 4     4   124236 use 5.008_003;
  4         13  
  4         136  
4 4     4   19 use strict;
  4         8  
  4         97  
5 4     4   18 use warnings;
  4         10  
  4         120  
6 4     4   17 use base 'Exporter';
  4         6  
  4         294  
7 4     4   21 use Scalar::Util qw(blessed reftype);
  4         7  
  4         1885  
8              
9             our $VERSION = '0.04';
10             our @EXPORT_OK = qw/to_array/;
11              
12             sub new {
13 7     7 0 3033 my $class = shift;
14 7         22 my $iterator = _is_iterable(shift);
15 6   33     37 $class = ref $class || $class;
16              
17 6         42 bless { iterator => $iterator }, $class;
18             }
19              
20             sub apply {
21 4     4 0 11 my $self = shift;
22 4         13 my $code = _is_coderef(shift);
23 4         16 my $iterator = $self->{iterator};
24 4         6 my @tmp;
25 4         15 while ( defined( my $r = $iterator->next() ) ) {
26 16         120 local $_ = $r;
27 16         30 push @tmp, $code->();
28             }
29 4 100       44 wantarray ? @tmp : \@tmp;
30             }
31              
32             sub to_array($&) {
33 2     2 0 1633 my ( $iterator, $code ) = @_;
34 2         12 __PACKAGE__->new($iterator)->apply($code);
35             }
36              
37             sub _is_iterable {
38 7     7   11 my $object = shift;
39 7 100 66     114 if ( $object && blessed($object) && $object->can('next') ) {
      66        
40 6         15 return $object;
41             }
42             else {
43 1         12 die "not a iterable object. object must have next method";
44             }
45             }
46              
47             sub _is_coderef {
48 4     4   6 my $code = shift;
49 4 50 33     29 if ( $code && reftype $code eq 'CODE' ) {
50 4         10 return $code;
51             }
52             else {
53 0           die "apply takes one code reference only";
54             }
55             }
56             1;
57             __END__