| [reply] |
You do realize that hash keys are not ordered in any meaningful way? So what purpose would interleaving them have? What homework is this for? | [reply] |
There is no first key in your hash - a hash by its very nature has no absolute first entry. keys will return a list of all keys in the hash in no particular order. You could therefore collect both sets of keys in arrays, and then splice them together. You could also use each. You could then cycle over them with Foreach Loops.
However, this sounds like an XY Problem. Why do you want to cycle over the lists? Chances are your final task in documented in perlfaq4 - my guess is How do I test whether two arrays or hashes are equal?.
As a side note, see how your array index got linkfied? The characters [ and ] have special meaning on this site - this is discussed in the text below the field where you typed your post. See Markup in the Monastery. | [reply] |
If, let us say, this isn’t an “XY problem,” here are three important things you need to ponder:
-
Elements in a hash are accessed only by key. They have no “order.” But you can get a list of all of the keys in order with sort keys hashref.
-
The data structure that you describe is “an array of hashrefs,” where each of these contains two keys ... (say) key and value.
-
Behold the magic of references. Notice that I said “hashref,” which is Perl-speak for “a reference to a hash.” A reference is exactly what it sounds like: “a thing” that refers to another “thing.” If you examine a reference, you examine what it refers to. If you change a reference, you change the thing that it refers to. (You can also make the reference refer-to a different “thing,” which is an altogether different notion.) So the array that I spoke of in #2 contains a list of “individual things,” as all arrays do, but each one of those “individual things” is a reference to something much more interesting ... each one of which, in turn, can contain “references to” something else, ad infinitum. Every one of those references has the power, not only to retrieve the value that it refers to, but to alter it.
Chew on this for a while, and then start chewing on perldoc perlref. (Chew slowly, and avoid looking directly at the light-bulbs because they have a habit of turning “on” at the strangest moments.)
| |
It seems reasonable to conclude from the question that you are satisfied with an arbitrary ordering of the hash keys for a particular hash, so in that case: my @array;
for my $href( \%hash1, \%hash2 ){
while( my ($k, $v) = each %{$href} ) {
push @array, { $k => $v };
}
}
| [reply] [d/l] |