Commits

Toby Inkster  committed ec7f7a3

NodeList->grep

  • Participants
  • Parent commits 1e82750

Comments (0)

Files changed (2)

File lib/XML/LibXML/NodeList.pm

 sub to_literal {
     my $self = CORE::shift;
     return XML::LibXML::Literal->new(
-            join('', grep {defined $_} CORE::map { $_->string_value } @$self)
+            join('', CORE::grep {defined $_} CORE::map { $_->string_value } @$self)
             );
 }
 
     return wantarray ? @results : (ref $self)->new(@results);
 }
 
+sub grep {
+    my $self = CORE::shift;
+    my $sub  = CORE::shift;
+    local $_;
+    my @results = CORE::grep { $sub->($_) } @$self;    
+    return wantarray ? @results : (ref $self)->new(@results);
+}
+
 1;
 __END__
 
 
 =head2 map($coderef)
 
-Equivalent to Perl's map function.
+Equivalent to perl's map function.
+
+=head2 grep($coderef)
+
+Equivalent to perl's grep function.
 
 =cut

File t/15nodelist.t

 use strict;
 use warnings;
 
-use Test::More tests => 17;
+use Test::More tests => 19;
 
 use XML::LibXML;
 use IO::Handle;
 # TEST
 is(join('|',@map2), '1|1|1|3|3|3|5|5|5|7|7|7|9|9|9', 'mapping can add/remove nodes');
 
+my @grep = $numbers->grep(sub {$_%2});
+my $grep = $numbers->grep(sub {$_%2});
+
+# TEST
+is(join('|',@grep), '1|3|5|7|9', 'grep works');
+
+# TEST
+isa_ok($grep => 'XML::LibXML::NodeList', '$grep');
+
+
 __DATA__
 <AAA>
 <BBB>OK</BBB>