View Single Post
Old 10-14-2003, 05:29 AM   #13 (permalink)
ratbastid
Darth Papa
 
ratbastid's Avatar
 
Location: Yonder
Quote:
Originally posted by peacy
A remark about the perl code:
In the "foreach" line when you use the when you use "keys" it's not necessary to write %$. The % is enough. Like this:
<code>
foreach my $key (sort {$rates->{$a} <=> $rates->{$b}} keys %rates)
</code>
Not when you're working with a hashref, it's not. The hash reference $rates must be "hashified" by spelling it %$rates as an argument to the keys() function. Otherwise you're talking about the HASH %rates which, in this code snippet, is undefined.

Try running the following code:

Code:
#!/usr/bin/perl

my $hashref;
my %hash;

%hash = ( a => 1, b => 2);
$hashref = \%hash;

print "Foreaching through \%hash:\n";
foreach my $key (keys %hash) {
&nbsp;&nbsp;print "$key -> $hash{$key}\n";
}

print "\nForeaching through \$hashref:\n";
foreach $key (keys %$hashref) {
&nbsp;&nbsp;print "$key -> $hashref->{$key}\n";
}

print "\nForeaching through \$hashref treated like a hash:\n";
foreach $key (keys %hashref) {
&nbsp;&nbsp;print "$key -> $hashref->{$key}\n";
}

print "\nDone!\n";
exit(0);
This is ANOTHER thing I've learned by making stupid one-character mistakes!
ratbastid is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52