H
Hein, Nashua NH
I have function which I'd like to call telling it how to sort some
arrays.
I'd like to do something like:
my $sort_by_x_ref = sub { return ($x{$b} <=> $x{$a})};
my $sort_by_y_ref = sub { return ($y{$b} <=> $y{$a})}
sub print_sorted {
my $sort_function = $_[0]->();
print "Sorted $_[1]\n";
foreach (sort {$sort_function} keys %some_array) {
:
print...
:
}
&print_sorted ( $sort_by_x_ref, "by X");
&print_sorted ( $sort_by_y_ref, "by Y" );
That does not work. {&$sort_function}, and just $sort_function do not
seem to work either.
Can this be done? What is the syntax?
My workaround is boring:
sub print_sorted {
print "Sorted $_[1]\n";
foreach (sort {($_[0]) ? $x{$b} <=> $x{$a} : $y{$b} <=> $y{$a} } keys
%some_array) {
:
print...
:
}
&print_sorted ( 1, "by X");
&print_sorted ( 0, "by Y" );
Please advice,
Hein.
arrays.
I'd like to do something like:
my $sort_by_x_ref = sub { return ($x{$b} <=> $x{$a})};
my $sort_by_y_ref = sub { return ($y{$b} <=> $y{$a})}
sub print_sorted {
my $sort_function = $_[0]->();
print "Sorted $_[1]\n";
foreach (sort {$sort_function} keys %some_array) {
:
print...
:
}
&print_sorted ( $sort_by_x_ref, "by X");
&print_sorted ( $sort_by_y_ref, "by Y" );
That does not work. {&$sort_function}, and just $sort_function do not
seem to work either.
Can this be done? What is the syntax?
My workaround is boring:
sub print_sorted {
print "Sorted $_[1]\n";
foreach (sort {($_[0]) ? $x{$b} <=> $x{$a} : $y{$b} <=> $y{$a} } keys
%some_array) {
:
print...
:
}
&print_sorted ( 1, "by X");
&print_sorted ( 0, "by Y" );
Please advice,
Hein.