Commits

Toby Inkster committed 4cee21f

NodeList->sort

Comments (0)

Files changed (2)

lib/XML/LibXML/NodeList.pm

     my $self = CORE::shift;
     my $sub  = CORE::shift;
     local $_;
-    my @results = CORE::map { @{[ $sub->($_) ]} } @$self;    
+    my @results = CORE::map { @{[ $sub->($_) ]} } @$self;
+    return unless defined wantarray;
     return wantarray ? @results : (ref $self)->new(@results);
 }
 
     my $self = CORE::shift;
     my $sub  = CORE::shift;
     local $_;
-    my @results = CORE::grep { $sub->($_) } @$self;    
+    my @results = CORE::grep { $sub->($_) } @$self;
+    return wantarray ? @results : (ref $self)->new(@results);
+}
+
+sub sort {
+    my $self = CORE::shift;
+    my $sub  = CORE::shift;
+    my @results = CORE::sort { $sub->($a,$b) } @$self;
     return wantarray ? @results : (ref $self)->new(@results);
 }
 
 
 Equivalent to perl's grep function.
 
+=head2 sort($coderef)
+
+Equivalent to perl's sort function.
+
+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.
+
 =cut
 use strict;
 use warnings;
 
-use Test::More tests => 19;
+use Test::More tests => 21;
 
 use XML::LibXML;
 use IO::Handle;
 # TEST
 isa_ok($grep => 'XML::LibXML::NodeList', '$grep');
 
+my $shuffled = XML::LibXML::NodeList->new(qw/1 4 2 3 6 5 9 7 8 10/);
+my @alphabetical = $shuffled->sort(sub { my ($a, $b) = @_; $a cmp $b });
+my @numeric      = $shuffled->sort(sub { my ($a, $b) = @_; $a <=> $b });
+
+# TEST
+is(join('|',@alphabetical), '1|10|2|3|4|5|6|7|8|9', 'sort works 1');
+
+# TEST
+is(join('|',@numeric), '1|2|3|4|5|6|7|8|9|10', 'sort works 2');
 
 __DATA__
 <AAA>