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

mpettis has asked for the wisdom of the Perl Monks concerning the following question:

Update: -- Thank you all very much... I am going to hack in Anonymous Monk's solution, and investigate the other two to see if they will work, as, per blazar, I really DON'T want to pass parameters to sort.

Thanks,

=========================================

Hi,

I want to build a sorting sub within a 'for' loop that is different based on a value within the scope of the 'for' loop. Can this be done? The variables I use in the sub do not seem to be visible within the customized sorting sub. I know that $a and $b are passed automatically to this function -- is there a way to pass in other arguments to the sorting sub other than $a and $b?

Thanks,

Matt
  • Comment on sorting function arcument to 'sort': Can I pass additional parameters?

Replies are listed 'Best First'.
Re: sorting function arcument to 'sort': Can I pass additional parameters?
by Anonymous Monk on Nov 10, 2008 at 04:35 UTC
    @list = sort { blah('whatever') } @list; sub blah { my $w = shift; return $a <=> $b; }
Re: sorting function arcument to 'sort': Can I pass additional parameters?
by f00li5h (Chaplain) on Nov 10, 2008 at 06:12 UTC

    If you are sorting by many fields Sort::Maker may be of some help too

    @_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;

Re: sorting function arcument to 'sort': Can I pass additional parameters?
by blazar (Canon) on Nov 10, 2008 at 10:22 UTC

    I personally believe that you don't want to "pass in other arguments to the sorting sub" because the sub is meant to be used sort and sort() itself won't pass anything in. Chances are you want to use closures instead:

    #!/usr/bin/perl use strict; use warnings; use 5.010; my @trans = ( sub { shift }, sub { ~ shift } ); my @unsorted = qw/foo bar baz/; for my $tr (@trans) { my @sorted = sort { $tr->($a) cmp $tr->($b) } @unsorted; say "@sorted"; } __END__
    --
    If you can't understand the incipit, then please check the IPB Campaign.