The Ghost
Jul 13 2005, 05:53 PM
How can I get the information out of the hashes?
sub somthing {
while (my $ref = $sth->fetchrow_hashref()) {
foreach my $col (keys %{$ref}) {
$results[$x]{$col}=$ref->{$col};
}
$x++;}
return (@results); }
Then later:
(I don't understand this part)
foreach my $result (@results) {
foreach my $key (keys {$results[$x]}) {
print "$key: $result{$key}n";
} }
Jeff 'japhy' Pinyan
Jul 13 2005, 02:03 PM
On Jul 13, The Ghost said:
QUOTE |
foreach my $col (keys %{$ref}) { $results[$x]{$col}=$ref->{$col}; } $x++;}
|
The @results array holds hash references...
QUOTE |
foreach my $result (@results) { foreach my $key (keys {$results[$x]}) {
|
Here you want to do:
foreach my $key (keys %$result) {
since each element in @results is a hash-ref, and $result is an element
from @results, you need to gets its keys. Since $result is a hash
reference, you need to write %$result to get at the hash.
QUOTE |
print "$key: $result{$key}n";
|
Likewise, that should be $result->{$key}.
--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://japhy.perlmonk.org/ % have long ago been overpaid?
http://www.perlmonks.org/ % -- Meister Eckhart
John W. Krahn
Jul 13 2005, 06:03 PM
The Ghost wrote:
QUOTE |
How can I get the information out of the hashes?
sub somthing { while (my $ref = $sth->fetchrow_hashref()) {
foreach my $col (keys %{$ref}) { $results[$x]{$col}=$ref->{$col}; } $x++;} return (@results); }
Then later: (I don't understand this part)
foreach my $result (@results) { foreach my $key (keys {$results[$x]}) { print "$key: $result{$key}n";
|
The value of $result is a reference to a hash so you have to dereference it
properly:
foreach my $key ( keys %$result ) {
print "$key: $result->{$key}n";
perldoc perldata
perldoc perllol
perldoc perldsc
John
--
use Perl;
program
fulfillment
Scott R. Godin
Jul 13 2005, 07:21 PM
Jeff 'japhy' Pinyan wrote:
QUOTE |
Here you want to do:
foreach my $key (keys %$result) {
since each element in @results is a hash-ref, and $result is an element from @results, you need to gets its keys. Since $result is a hash reference, you need to write %$result to get at the hash.
|
I've never liked the way
%$somevar
which, while legal syntax, looks. Too easy to visually confuse, whereas
%{$somevar}
is much clearer that we're dereferencing a hashref, and that if you want
to extract a value, you instead hang the {}'s off of the dereference
operator -> as in
$somevar->{$key}
While it requires two extra keystrokes, it definitely improves
maintainability, to my eye. (particularly when staring blearily at code
in the wee hours of the morning wondering why it won't work. :)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please
click here.