Commits

Toby Inkster committed 4d69dc1

NodeList->foreach

Comments (0)

Files changed (2)

lib/XML/LibXML/NodeList.pm

     return wantarray ? @results : (ref $self)->new(@results);
 }
 
+sub foreach {
+    my $self = CORE::shift;
+    my $sub  = CORE::shift;
+    $self->map($sub);
+    return $self;
+}
+
 1;
 __END__
 
 Caveat: Perl's magic C<$a> and C<$b> variables are not available in
 C<$coderef>. Instead the two terms are passed to the coderef as arguments.
 
+=head2 foreach($coderef)
+
+Inspired by perl's foreach loop. Executes the coderef on each item in
+the list. Similar to C<map>, but instead returning the list of values
+returned by $coderef, returns the original NodeList.
+
 =cut
 use strict;
 use warnings;
 
-use Test::More tests => 21;
+use Test::More tests => 23;
 
 use XML::LibXML;
 use IO::Handle;
 # TEST
 is(join('|',@numeric), '1|2|3|4|5|6|7|8|9|10', 'sort works 2');
 
+my $reverse = XML::LibXML::NodeList->new;
+my $return  = $numbers->foreach( sub { $reverse->unshift($_) } );
+
+# TEST
+is(
+  blessed_refaddr($return),
+  blessed_refaddr($numbers),
+  'foreach returns $self',
+  );
+
+# TEST
+is(join('|',@$reverse), '10|9|8|7|6|5|4|3|2|1', 'foreach works');
+
+
+# modified version of Scalar::Util::PP::refaddr
+# only works with blessed references
+sub blessed_refaddr($) {
+  return undef unless length(ref($_[0]));
+  my $addr;
+  if(defined(my $pkg = ref($_[0]))) {
+    $addr .= bless $_[0], 'Scalar::Util::Fake';
+    bless $_[0], $pkg;
+  }
+  $addr =~ /0x(\w+)/;
+  local $^W;
+  hex($1);
+}
+
+
 __DATA__
 <AAA>
 <BBB>OK</BBB>