Examples:
%hash = (2010 => 21, 2009=> 9);
$hash = {
a => {
0 => {test => 1},
1 => {test => 2},
2 => {test => 3},
3 => {test => 4},
},
};
How do I print the hash?
Examples:
%hash = (2010 => 21, 2009=> 9);
$hash = {
a => {
0 => {test => 1},
1 => {test => 2},
2 => {test => 3},
3 => {test => 4},
},
};
How do I print the hash?
The function printStruct below works using recursion and can print hashes of arrays, arrays of hashes or any mixture thereof to any depth. You call it with a reference to your structure, and a name of the structure in a string. The last input $pre is only used during the recursion to tell the initial entry into the recursive function. Just leave it blank when you call the function.
Result:
This function helped in a lot of programming and debugging of complex structures. I hope you guys find it as useful.
instead of
you should write
with the curly braces you get a REFERENCE to an anonymous hash, which is then stored as the first key of you %hash.
Do you want to print the entire hash, or specific key, value pairs? And what is your desired result? IF it's just for debugging purposes, you can do something like:
You can use the
each
function if you don't care about ordering:Or the
for
/foreach
construct if you want to sort it:Or if you want only certain values, you can use a hash slice, e.g.:
etc, etc. There is always more than one way to do it, though it helps to know what you're frying to do first :)
Syntax to access inner cells for your second example is like:
That will give you 1 in your example.
If you want to iterate on it, you can do it as follows (print lines are for illustration purposes):
Notice that things are a bit more tricky than necessary because the external $hash is a scalar reference to an anonymous hash. It would be simpler if it was a hash (i.e., like in
my %hash = (1, 2); print $hash{1};
).(TIMTOWTDI: there is obviously more than one way to do it; I believe the above example is the simplest for me, but not the most efficient; using
each
instead ofkeys
for iterating would avoid one unnecessary hash lookup).