Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Pass additional params into sub which create sorting rules

by sgifford (Prior)
on Dec 04, 2007 at 06:35 UTC ( [id://654724]=note: print w/replies, xml ) Need Help??


in reply to Pass additional params into sub which create sorting rules

A useful technique is to create a "sorter factory", which will create a new sub which remembers the sort parameters, then return that sub to be used by sort. In Perl parlance, this is called storing the parameters in a lexical variable and creating a sub which closes around that lexical. For example:
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @xx = ( 'dfb|cy|nmju', 'dfb|my|jhiho', 'aaa|zz|gggg' ); my $sorter = make_sorter(2); my @sorted_xx = sort $sorter @xx; print Dumper \@xx; print Dumper \@sorted_xx; sub make_sorter { my($col)=@_; return sub { my @arr_a = split /\|/, $a; my @arr_b = split /\|/, $b; return $arr_a[$col] cmp $arr_b[$col]; }; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://654724]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2024-04-26 00:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found