You've got one major problem with that code, as written, as well as a number of style issues, which can cause further problems.
sub GetReferersBar{
my ($key,$value,%thishash,$bartext);
# This line simply asserts that $i, when first declared and
# converted to a number is zero.
my ($i)==0;
my ($nrefs,$n1,$n2);
sub by_value { $a <=> $b };
sub printcells {
my ($maxcols,$reference_to_values)=@_ ;
my ($i,$html);
my %thishash = %{$reference_to_values};
sub by_nhits { $thishash{$b}<=>$thishash{$a} };
foreach $key (sort by_nhits keys %thishash) {
$html .= "<TR><TD>$thishash{$key}"
}
return $html
}
$bartext = "<TABLE>";
$bartext .= &printcells($nrefs,\%ThisHash);
$bartext .= &printcells($nrefs,\%AnotherHash); # LINE A <-- probl
+em
$bartext .= "</TABLE>" ;
return $bartext;
}
The style issues are too numerous to state in that snippet. You're an ANSI C programmer by training, aren't you? :-)
Try doing something like this:
sub printcells {
my $href = shift;
my $html;
$html .= "<TR><TD>$thishash{$_}</TD></TR>"
foreach sort { $href->{$b} <=> $href->{$a} } keys %$thishash;
return $html
}
sub GetReferersBar {
my ($thisHash, $anotherHash) = @_;
my $bartext = "<TABLE>";
$bartext .= printcells($thisHash);
$bartext .= printcells($anotherHash);
$bartext .= "</TABLE>" ;
return $bartext;
}
Notice the difference? Now, you have to pass in the references to %ThisHash and %AnotherHash. All the unused variables are removed and the useless creation of the sub to sort a specific situation is removed, instead showing that the sort is specific to that spot.
Now, if you want to have by_nhits() be in a module, I would suggest rethinking how it should work. All you're doing is a reverse numeric sort on the values of the hashes you're working with. Why not just do a reverse numeric sort on the values, maybe like this:
foreach my $key (map { $_->[0] }
sort { $b->[1] <=> $a->[1] }
map { [ $_, $thishash->{$_} ] }
keys %$thishash;
This is known as the Schwartzian Transform. You create a listref of (generally) two elements. The first element(s) is the one you care about and the second element(s) is the one you want to sort on. You sort on the second element(s) and give back the first element(s). This way, you can create a ST_by_reverse_numeric() that's generic now. If you were to put it in a module, it could look something like this:
sub ST_by_reverse_numeric {
local ($a, $b);
$b->[1] <=> $a->[1]
}
The locals are to allow for the import of the sorting function. If you really want to know why that is needed, look around the monastery. We've discussed at least twice in the last month.
------ We are the carpenters and bricklayers of the Information Age. Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement. |