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.
You can extract all the values from a hash with the
values
function:If you want them in a particular order, then you can put the keys in the desired order and then take a hash slice from that:
Combining FM's and Ether's answers allows one to avoid defining an otherwise unnecessary scalar:
The neat thing is that unlike with the
scalar
approach,$#
works above even in the unlikely event that the default index of the first element,$[
, is non-zero.Of course, that would mean writing something silly and obfuscated like so:
But then there is always the remote chance that someone needs it somewhere (wince)...
We can write a while as below:
$a1 contains the key and $b1 contains the values In the above example i have Hash of array and the array contains 6 elements.
If your original data source is a hash:
Or if your original data source is a hashref:
This is easy to test using this example: