http://www.perlmonks.org?node_id=376989


in reply to Re: CPAN module fior common idioms?
in thread CPAN module fior common idioms?

I agree with you, but you got me thinking. How about this:
#usage: @result = st_complex sub { complex comparison }, sub { transfo +rm }, LIST sub st_complex (&&@) { my $compare = shift; my $transform = shift; map { $_->[-1] } sort $compare map { [ $transform->(), $_ ] } @_; } #usage: @result = st_simple sub { transform }, LIST #note: comparison is string wise. sub st_simple (&@) { my $transform = shift; &st_complex(sub { $a->[0] cmp $b->[0] }, $transform, @_); }
The only shortcomings I can find are that sub NAME (&&@) won't allow you to call NAME { CODE } { CODE } LIST, only the first code block can be a bare block, and I can't thing of an effective way to combine the two into a single function like sort.

Replies are listed 'Best First'.
Re^3: CPAN module fior common idioms?
by ihb (Deacon) on Jul 24, 2004 at 02:49 UTC

    I thought about this too, when writing my reply to Re: CPAN module fior common idioms?. But I did three distict different design choices. My sort call looks like this:

    my @foo = qw/ a3 b2 r4 s1 /; print for STsort( sub { /(\d+)$/ }, sub { $_[0][1] <=> $_[1][1] }, @foo ); __END__ s1 b2 a3 r4
    The differences are:
    • Order of the subs: I feel it's more natural to first see the transformation and then how that transformation should be sorted, as the sort sub means nothing if you haven't seen the transformation sub. An inlined ST is read backwards.
    • $_[0] instead of $a: &STsort can't, without voodoo AFAIK, in every case realize which $a and $b to use.
    • Original at index 0: I put the original value at the beginning of the array instead of at the end. I feel this is nicer when I don't know the length of the result of the transformation.

    ihb

    Read argumentation in its context!