Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

sorting function arcument to 'sort': Can I pass additional parameters?

by mpettis (Beadle)
on Nov 10, 2008 at 04:16 UTC ( #722547=perlquestion: print w/ replies, xml ) Need Help??
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?
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://722547]
Approved by lamp
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-12-20 04:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls