If I have a hash in Perl that contains complete and sequential integer mappings (ie, all keys from from 0 to n are mapped to something, no keys outside of this), is there a means of converting this to an Array?
I know I could iterate over the key/value pairs and place them into a new array, but something tells me there should be a built-in means of doing this.
An easy way is to do
@array = %hash
For example,
print "@array";
would produce the following output,This will leave keys not defined in
%hashed_keys
asundef
:And, if you're using references:
Or, more dangerously, as it assumes what you said is true (it may not always be true … Just sayin'!):
But this is sort of beside the point. If they were integer-indexed to begin with, why are they in a hash now?
OK, this is not very "built in" but works. It's also IMHO preferrable to any solution involving "sort" as it's faster.
Otherwise, less efficient:
Perl does not provide a built-in to solve your problem.
If you know that the keys cover a particular range
0..N
, you can leverage that fact:As DVK said, there is no built in way, but this will do the trick:
or this:
benchmark to see which is faster, my guess would be the second.