sorting - unit test for Perl's sort -
i try use (class) method in object sorting object instances.
package something; use strict; use warnings; use data::dumper; sub new { ($class, $date) = @_; $self = bless{}, $class; $self->{date} = $date; return $self; } sub _sort($$) { print stderr dumper($_[0], $_[1]); $_[0]->{date} cmp $_[1]->{date}; } package somethingtest; use base 'test::class'; use test::more; __package__->runtests() unless caller; sub sorting : test { $jan = something->new("2016-01-01"); $feb = something->new("2016-02-01"); $mar = something->new("2016-03-01"); is_deeply( sort something::_sort [$feb, $mar, $jan], [$jan, $feb, $mar]); }
i've seen snippet in perldoc -f sort
, hence prototype _sort
.
# using prototype allows use comparison subroutine # sort subroutine (including other package's subroutines) package other; sub backwards ($$) { $_[1] cmp $_[0]; } # $a , $b # not set here package main; @new = sort other::backwards @old;
however, dumped arguments odd:
$var1 = [ bless( { 'date' => '2016-02-01' }, 'something' ), bless( { 'date' => '2016-03-01' }, 'something' ), bless( { 'date' => '2016-01-01' }, 'something' ) ]; $var2 = [ $var1->[2], $var1->[0], $var1->[1] ];
and test fails with
# failed test 'sorting died (not hash reference @ sort.t line 16.)' # @ sort.t line 25.
is test setup or can't have same objects in these arrays? else missing?
your problem isn't subroutine pass sort()
, in arguments pass is_deeply()
. way have written parses this, if add parentheses:
is_deeply( sort(something::_sort [$feb, $mar, $jan], [$jan, $feb, $mar] ) );
that is, you're telling sort()
act on list consisting of 2 anonymous array references, , is_deeply()
run single argument returned sort
(except crashes before is_deeply()
can try run , complain gave few arguments work with).
this closer intended:
is_deeply( [sort(something::_sort ($feb, $mar, $jan))], [$jan, $feb, $mar]);
that is, tell is_deeply()
compare 2 anonymous arrays, first of made telling sort()
apply sorting routine list ($feb, $mar, $jan)
.
Comments
Post a Comment