Search code examples
perl

How to convert hash to array without the use of intermediate variable?


How to convert hash to to array temporarily without using intermediate variable

For example in the following code "@arr" variable is an array storing the converted hash.

my %scientists = (
    "Newton"   => "Isaac",
    "Einstein" => "Albert",
    "Darwin"   => "Charles",
);

my @arr = %scientists;
print $_ . " " foreach @arr; # "Newton Isaac Darwin Charles Einstein Albert"

I am not trying to accomplish anything specific here. Just want to know if its possible to convert hash to an array wihtout intermediate variable

print ref(\@arr); # print array

similarly is there a something that can replace "" so that the following is possible

print ref(<syntax>%scientists%<sytax>) # should print array.

Solution

  • In list context, %hash results in a key-value pairs of scalars.

    For example, %scientists results in the six scalars "Newton", "Isaac", "Einstein", "Albert", "Darwin", "Charles", although the order can vary.

    This applies on the right-hand side of my @arr =.

    my @arr = %scientists;
    

    And it also applies for the list of a foreach loop.

    print $_ . " " for %scientists;
    

    Most of the time, however, one would use keys( %scientists ) instead of just %scientists.

    say "$_ $scientists{ $_ }" for keys( %scientists );
    

    For the question at the bottom, you could use

    say ref( [ %scientists ] );
    

    [ ... ] is roughly equivalent to do { my @anon = ...; \@anon }.

    In other words, it still creates an array, but the array is anonymous.