Newbies often overthink the problem and use too much code. As code gets more complex, there is a greater chance of bugs, and it becomes less readable and harder to maintain. Here's a more concise version with notes for your education.

# always use strict & warnings # they give useful debugging info use strict; use warnings; # get your rawdata my @rawdata = ... # chomp the whole array at once chomp @rawdata; # declare the hash my %ipkey; # a 'C' style for loop is useful here # this one loops over every second array index for (my $i = 0; $i < @rawdata; $i += 2){ # get each pair of consecutive items from array my $key = $rawdata[$_]; my $value = $rawdata [$_ + 1]; # then build the hash $ipkey{$key} = $value; # and print your results print "Key: $key <br>Value: $value<br><br>"; # if printing to the console, do this instead print "Key: $key \nValue: $value\n\n"; }

Update:

Also note that arrays can be directly assigned to hashes.

# direct assignment my %ipkey = @rawdata; # iterate over hash keys & print for (keys %ipkey) { print " Key: $_ \n Value: $ipkey{$_} \n\n"; }

In reply to Re: Creating hash with variables by hangon
in thread Creating hash with variables by vonedaddy

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.