in reply to Creating hash with variables
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"; }
|
---|