|
Posted by xhoster on June 12, 2008, 11:57 am
Please log in for more thread options > wrote:
>
> >> i highly doubt this is a perl bug. my gut feeling is that you have
> a
> > scoping problem. the first sort keeps $a and $b inside the sort block
> > and those will be set correctly. if you lexically declared $a and $b in
> > your code before the by_value sub, those will be used and screw up your
> > sort. or maybe a different $site is being used because it is in a
> > different scope. you need to post more code so we can see the
> > problem. it isn't just with the above code.
>
> I suspect your are right and I have done something *really* stupid -
> but I get the same on a Solaris system. $a & $b are correct and from
> the correct $site.
>
>
> my $site;
You should declare variables in the tightest scope you can, otherwise
use strict will be less helpful in finding such scoping problems.
...
> foreach $site (keys %sites)
it would be better to use "foreach my $site"
> {
> print "\nSite: $site\n";
>
> foreach my $url (sort by_value keys %})
> {
> print "$site $url $urls[0] $urls[1]\n";
> }
> }
The way foreach works, the $site inside the loop is not the same
as the $site declared outside the loop.
>
> sub by_value
> {
> print "Sort site: >$site< $a $b\n";
> $urls[0] <=> $urls[0] or $a cmp $b;
> }
The $site used by by_value is the one from outside the foreach loop, not
the one inside the foreach loop. Usually you'd just pass in $site as an
argument, but when the sub is called automatically from sort, that doesn't
work.
There are a variety ways around this, but none of them are entirely
satisfactory. One would be to make the sub an ordinary subroutine,
rather than one made specifically to be used by sort, then invoke
it explicitly rather than implicitly:
foreach my $url (sort keys %})
...
sub by_value
{
my ($a,$b,$site)=@_;
print "Sort site: >$site< $a $b\n";
$urls[0] <=> $urls[0] or $a cmp $b;
}
Xho
--
-------------------- http://NewsReader.Com/ --------------------
The costs of publication of this article were defrayed in part by the
payment of page charges. This article must therefore be hereby marked
advertisement in accordance with 18 U.S.C. Section 1734 solely to indicate
this fact.
|