Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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:

In reply to Re: Re: Re: Closures and sort by larsen
in thread Closures and sort by traveler

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-04-16 17:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found