Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

Comment on Creating hash with variables
Download Code
Re: Creating hash with variables
by colwellj (Monk) on Feb 11, 2010 at 04:12 UTC
    vonedaddy,
    First can you show some sample data please.
    thanks
    John
      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'
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.

      66.249.90.104 www.google.com

      74.52.141.211 www.focusfaction.com

      209.197.123.153 www.perlmonks.com

      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 (209.197.123.153 , 66.39.54.27 for PerlMonks) and multiple domains might resolve to the same IP address(es) (perlmonks.org , perlmonks.net and perlmonks.com 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 (Parson) 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"; }

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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://822574]
Approved by bobf
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2014-12-27 23:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls