print $Data{logins}[0]{url};
| [reply] [d/l] |
Thank you for the Perl data structure cookbook. Your code did not work but it sure gave me a place to look how to solve this.
Since this was nested I needed to refrence it with arrows. Thanks so much for your help. I am bookmarking this link too.
Here is the code that worked.
print $Data->{logins}->[0]->{url};
| [reply] [d/l] |
print $Data->{logins}[0]{url};
| [reply] [d/l] |
Can you give an example?
Generally, I find that spitting a deep structure out using Data::Dumper (or even Data::Dump) can make complicated queries like this much more obvious. Have you tried that?
| [reply] |
I don’t much care for Data::Dumper’s look. I much prefer the output from the Dumpvalue module for this sort of thing. It’s what the Perl debugger uses. Data::Dumper is a serialization module, whereas Dumpvalue’s job is to show you the data structure in a good-looking way. That doesn’t mean it has to be eval()able.
| [reply] |
| [reply] |
You explain with an example data. Now I tried with an example hash according to your description. If I understood your hash structure wrongly, you give the example data.
use strict;
use warnings;
use Data::Dumper;
my %hash=("logins" => [ { '1' => 'http://www.perlmonks.com/?node_id=90
+1658' , '2' => 'http://www.google.com' }, { '3'=> 'http://www.bksyste
+ms.co.in'}]);
#prints the structure of the hash
print Dumper \%hash;
print "==========================\n";
# getting the length of an array and going through each index of an ar
+ray
for (0 .. length @{$hash{'logins'}}) {
for my $key (keys%{$hash{'logins'}[$_]}) {
# printing key and value
print "Key: $key and Value:$hash{'logins'}[$_]{$key}\n";
+
}
print "==========================\n"
}
| [reply] [d/l] |
Short, specific examples would be nice.
The key notion that you need to wrap your mind around is references. (See perlref.)
A “reference” is a Thing, that “refers to” another Thing somewhere else. So when you have “an array of hashes,” the more proper way to say it is that you have “an array of hashrefs.” (The word, “hashref,” is simply a shorthand way of saying, “a reference to a hash.”) So, the data structure itself, is over here, and there are lots of “references to” that data structure scattered about in other places. (Think about that for a little while, until the light-bulb pops on. And I don’t mean that to sound condescending.) It’s very much like “pointers,” but considerably more sturdy.
Arbitrarily complex data-structures can be built using this mechanism. You might need to read up on weaken in Scalar::Util, but that’s another idea for another day...
There are several ways to write this code, and all of those ways work equally well. It’s quite important to use use strict and use warnings when writing this kind of code, but otherwise, Perl is quite generous and forgiving in its syntax rules.
| |