> The purpouse of this mini-script is to list the rows from a database loaded > in memory ($ref_db is the reference to hashtable that cotains the DB). So I > want to order the fields by different sort rules, and make the proccess as > abstract as it's possible with a subrutine (sub cmpRule). This sub must > recieve the rules (by array argument, for example), and create the body that > will be called by sort. >
[deletia...] > It works but, do you think it's a good solution? I think that was a highly suboptimum solution. #!/usr/bin/perl use strict; use warnings; # # hashref? Why in the WORLD is the database being kept in a hashref? # my $data_for = { apple => { color => 'verde', name => 'manzana', texture => 'crujiente' }, banana => { color => 'amarillo', name => 'platano', texture => 'blando' }, strawberry => { color => 'roja', name => 'fresa', texture => 'blanda' }, }; # # if you have a small number of columns you want to sort by, build a # simple subroutine to sort by that column -- this is *FAR SUPERIOR* # to building a throw-away subroutine and eval-ing it at run time. # sub by_color { return $a->{color} cmp $b->{color} }; sub by_name { return $a->{name} cmp $b->{name} }; sub by_texture { return $b->{texture} cmp $b->{texture} }; # # now, pass into sort a subref for the sort function to use # foreach my $sortkey (\&by_color, \&by_name, \&by_texture) { print "\n\n"; foreach my $row (sort $sortkey values %$data_for ) { print "$row->{color} - $row->{name} - $row->{texture}\n"; } } # # if you have hundreds of fields you want to sort by, then you should # do this slightly uglier version (uglier because it uses a # package-global to hold the current sort column # our $current_sort_field; sub by_something { return $a->{$current_sort_field} cmp $b->{$current_sort_field}; } foreach $current_sort_field (qw/ color name texture /) { print "\n\nSorting by $current_sort_field\n"; foreach my $row (sort by_something values %$data_for ) { print "$row->{color} - $row->{name} - $row->{texture}\n"; } } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Lawrence Statton - [EMAIL PROTECTED] s/aba/c/g Computer software consists of only two components: ones and zeros, in roughly equal proportions. All that is required is to sort them into the correct order. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>