Perl, convert hash to array

后端 未结 11 2251
借酒劲吻你
借酒劲吻你 2021-02-05 06:56

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 mean

11条回答
  •  眼角桃花
    2021-02-05 07:24

    Combining FM's and Ether's answers allows one to avoid defining an otherwise unnecessary scalar:

    my @array = @hash{ 0 .. $#{[ keys %hash ]} };
    

    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:

    my @array = @hash{ $[ .. $#{[ keys %hash ]} };   # Not recommended
    

    But then there is always the remote chance that someone needs it somewhere (wince)...

提交回复
热议问题