The obvious answer would be to add a method reset_count() in the block, but you would have to explicitly call it before sorting, which is prone to errors.
Another way is to put together a state and a behaviour, building an object.
But if you want to go on in a functional way, you may want to build a composition of a behaviour and a state, i.e. a
closure. Here a short demonstration:
use strict;
my @list1 = qw/ box cow dog apple ant/;
my @list2 = qw/ ant apple box cow dog/;
sub make_a_profilable_sorter
{
my $criterion = shift;
return sub {
my $counter = 0;
my @list = @_;
@list = sort { $counter++; $criterion->( $a, $b ) } @list;
return ( $counter, @list );
}
}
my $sorter1 = make_a_profilable_sorter( sub{ $_[0] cmp $_[1] } );
my $sorter2 = make_a_profilable_sorter( sub{ $_[0] cmp $_[1] } );
my ($count, @res) = $sorter1->( @list1 );
print "I sorted /@list1/ in $count steps producing /@res/\n";
my ($count, @res) = $sorter2->( @list2 );
print "I sorted /@list2/ in $count steps producing /@res/\n";
In order to learn more about this subject (very interesting, in my opinion) you could refer to the following online resources: