D
Dave Saville
This started out as one question but in trying to solve my problem I
got side tracked - as you do
In the "Perl Cookbook" page 140 under sorting lists there is the
following code:
@ordered = sort { $a->name cmp $b->name } @employees;
Where has 'name' come from? and what is in @employees such that
$a->name means something? I can't work it backwards as it were to
figure it out.
Now the actual problem.
I have a script that is building an HTML table. The table is built
from a hash. The top level entries of the hash are anonymous arrays
the elements of which are the columns.
At present there is a chunk of duplicated formatting code depending on
which of two columns I sort over. Yesterday the inevitable happened in
that I changed the formatting of one set and forgot to make the same
change in the other. The "curse of the duplicated code"
So it got me wondering if I could code one formatting loop and
dynamically set the sort up or down.
$foo = \&sortup;
$foo = \&sortdown if $bar;
foreach (sort $foo keys ......
But I recall scope problems in the past using suborutines that seem
solved if one used sort { ..... } syntax
At present one of the sorts looks like:
foreach my $url (sort {$$urlsref{$site}{$b}[0] <=>
$$urlsref{$site}{$a}[0] or $a cmp $b} keys %{$$urlsref{$site}} ) #
count descending
TIA
got side tracked - as you do
In the "Perl Cookbook" page 140 under sorting lists there is the
following code:
@ordered = sort { $a->name cmp $b->name } @employees;
Where has 'name' come from? and what is in @employees such that
$a->name means something? I can't work it backwards as it were to
figure it out.
Now the actual problem.
I have a script that is building an HTML table. The table is built
from a hash. The top level entries of the hash are anonymous arrays
the elements of which are the columns.
At present there is a chunk of duplicated formatting code depending on
which of two columns I sort over. Yesterday the inevitable happened in
that I changed the formatting of one set and forgot to make the same
change in the other. The "curse of the duplicated code"
So it got me wondering if I could code one formatting loop and
dynamically set the sort up or down.
$foo = \&sortup;
$foo = \&sortdown if $bar;
foreach (sort $foo keys ......
But I recall scope problems in the past using suborutines that seem
solved if one used sort { ..... } syntax
At present one of the sorts looks like:
foreach my $url (sort {$$urlsref{$site}{$b}[0] <=>
$$urlsref{$site}{$a}[0] or $a cmp $b} keys %{$$urlsref{$site}} ) #
count descending
TIA