Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Creating hash with variables

by vonedaddy (Initiate)
on Feb 11, 2010 at 04:04 UTC ( #822574=perlquestion: print w/replies, xml ) Need Help??
vonedaddy has asked for the wisdom of the Perl Monks concerning the following question:

I am new to perl (first language so no programming background either) and need help solving a problem I am having. I am writing some code to check DNS records and I am stumped here. I an trying to create a hash from user input. Here is the code, for some reason I can not populate the hash (keys or values) using a variable. Any help is appreciated.

NOTE: print statements were for debugging :)

$count = 0; foreach (@rawdata) { #Remove newline if ($count == 0) { $key = $_; $count++; chomp $key; print "Key: $key<br>"; next; } if ($count == 1) { $value = $_; $count++; chomp $value; print "Value: $value<br><hr>"; } if ($count == 2) { $ipkey{'$key'} = '$value'; $count = 0; print $ipkey{$key}; } }

Replies are listed 'Best First'.
Re: Creating hash with variables
by bobf (Monsignor) on Feb 11, 2010 at 04:12 UTC

    Single quotes do not interpolate, so your hash does not contain what you think it does. Add this to the top of your code:

    use strict; use warnings; use Data::Dumper;
    then after your foreach loop do this:
    print Dumper \%ipkey;

    That said, there are likely much easier ways to do what you are trying to accomplish. If you are interested, post some example data and explain what you are trying to do. Monks love that kind of thing.

    Psst... just for fun, try this:

    %ipkey = @rawdata;

      First off THANK YOU all for the replies.

      Here is some example data that a user would put into a web page which will be passed to this perl script.

      I am writing this code to do some checks on DNS records before we (I work on a DNS team) add the records. I wanted to place the IP address from the input into a hash key and make the value the fqdn. This way I can dig against the IP and then see if what is returned matches whats in the hash. This would tell us that the record exists and matches what we expected and no action is needed. This is just one part of a larger DNS validation script I am writing (or attempting to write).

      Thanks in advance for all your help

        Note that for general DNS applications, a hash is not necessarily the best choice of data structure, because one domain might resolve to different IP addresses ( , for PerlMonks) and multiple domains might resolve to the same IP address(es) ( , and use these two IP addresses). But for well-known, "major" IP addresses, a simple hash lookup might be what's needed.

Re: Creating hash with variables
by Anonymous Monk on Feb 11, 2010 at 04:14 UTC
    $key = 'something'; print '$key', "\n"; print "$key", "\n"; print $key, "\n"; __END__ $key something something
    See interpolate in perlintro
Re: Creating hash with variables
by dsheroh (Prior) on Feb 11, 2010 at 08:47 UTC
    $ipkey{'$key'} = '$value';

    Aside from the interpolation issue already mentioned by previous answers, this is a useless use of quotes. You want to use the values of the variables, not their names, and you aren't trying to insert them into a larger string, so don't quote them at all:

    $ipkey{$key} = $value;

Re: Creating hash with variables
by hangon (Deacon) on Feb 11, 2010 at 14:57 UTC

    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"; }


    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"; }
Re: Creating hash with variables
by colwellj (Monk) on Feb 11, 2010 at 04:12 UTC
    First can you show some sample data please.
      This works.
      #!/usr/bin/perl -w use strict; my (%ipkey,$value,$key); my $count = 0; my @rawdata = ('key1','value1','key2','value2','key3','value3'); foreach (@rawdata) { if ($count == 0) { $key = $_; $count++; next; }else{ $value = $_; $ipkey{$key} = $value; $count = 0; } }<\code> <br> OUTPUT<code> DB<4> x %ipkey 0 'key2' 1 'value2' 2 'key1' 3 'value1' 4 'key3' 5 'value3'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://822574]
Approved by bobf
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2018-02-26 04:21 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (316 votes). Check out past polls.