http://www.perlmonks.org?node_id=938540

jojojo has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Im new to PERL and thus stuck with something. I have an array which contains two elements. I want to create a hash such that the first element is the key for the second element. How do I do that? I tried a few things but nothing seems to be working.

my %sizes = map { "$symbolsizes[0]" => "$symbolsizes[1]" } ;

Replies are listed 'Best First'.
Re: How to create hash out of an array elements?
by wfsp (Abbot) on Nov 17, 2011 at 08:49 UTC
Re: How to create hash out of an array elements?
by ikegami (Patriarch) on Nov 17, 2011 at 09:07 UTC

    The map callback never gets called since you didn't pass any list to transform, so map returns nothing.

    You could create the desired list of two elements as follows:

    my %sizes = ( $symbolsizes[0] => $symbolsizes[1] );

    But really, all you need is the following:

    my %sizes = @symbolsizes;

    PS — The language is called "Perl", not "PERL".

      Thanks. This seems to be working. Now I am not able to print the values. The following code works:

      print "The size for $symbolsizes[0] is $sizes{$symbolsizes[0]}";
      But when I specify the name, it doesnt work. And this code is of no use if it can't print the values when the function name is specified. Please help.
      print "The size for function is $sizes{function}";

      Assume function to be an element of the array symbolsizes.

        Then $symbolsizes[0] doesn't contains function. Perhaps it contains a trailing newline that you didn't remove using chomp?

Re: How to create hash out of an array elements?
by CountZero (Bishop) on Nov 17, 2011 at 10:47 UTC
    This works:
    use Modern::Perl; my %sizes = ('function' => 100, 'another function' => 200); say "The size of function is $sizes{'function'}";
    Output:
    The size of function is 100

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: How to create hash out of an array elements?
by ansh batra (Friar) on Nov 17, 2011 at 09:38 UTC
    @arr=(1,2,3,4,5,6,7,8,9,10); %hsh= (); $i=0; while($i<10) { $hsh{$arr[$i]}=$arr[$i+1]; $i=$i+2; } while ( my ($key, $value) = each(%hsh) ) { print "$key => $value\n"; }

    output
    1 => 2 3 => 4 7 => 8 9 => 10 5 => 6