Hello alialialia,

As already said you can feed a list to form an hash directly. But note venoth.ree added use warnings (and use strict too: never miss them) infact if your list is odd you can trap some unwanted behaviour:

perl -we "my %hash = @ARGV" Andy 1995 Sarah 1990 Sam 1992 UNEXPECTED Odd number of elements in hash assignment at -e line 1.

If you want to build the hash using a loop (ignoring odd element if present), you can use while as in:

@ARGV = qw( Andy 1995 Sarah 1990 Sam 1992 UNEXPECTED ); my %hash; while (my $key = shift @ARGV and my $val = shift @ARGV){ $hash{$key}=$val } # hash is: ("Sam", 1992, "Andy", 1995, "Sarah", 1990)

UPDATE you can spot the odd element before entering the loop: print qq(odd element $ARGV[-1] will be lost!\n) if @ARGV % 2 > 0; though.

If you want you can also explore List::Util pairs function: it warns on odd element assigning undef

use strict; use warnings; use List::Util qw(pairs); @ARGV= qw(Andy 1995 Sarah 1990 Sam 1992 UN); my %hash; for my $pairs (pairs @ARGV){ $hash{ $$pairs[0] } = $$pairs[1]; } Odd number of elements in pairs at -e line 1. # hash is: ("Sarah", 1990, "Andy", 1995, "UN", undef, "Sam", 1992)
L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

In reply to Re: How to change an Array to a Hash (updated) by Discipulus
in thread How to change an Array to a Hash by alialialia

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.