at2marty has asked for the wisdom of the Perl Monks concerning the following question:
Here is what I am trying to do. I want to open the hosts file on my machine (Linux) and read the first two columns into a hash that will give me the ip address as the key, and the hostname as the value.
I've done some googling on the subject, and can't seem to find a clear answer.
I can read the contents of the hosts file into an array with no problem, but can't seem to get a good grasp of how to do so into a hash.
Here is an example of one of the things that I tried.
#!/usr/bin/perl -w use strict; my $hostfile = "/etc/hosts"; my %hosts = (); open FILE, "<", "$hostfile" || die "Cannot open $hostfile $!"; while (<FILE>) { chomp; my ($key, $value) = split (" ", $_); $hosts{$key} = $hosts{$value}; } close FILE;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How To Read Hosts File Into a Hash
by onelesd (Pilgrim) on Sep 15, 2011 at 23:26 UTC | |
by keszler (Priest) on Sep 16, 2011 at 00:05 UTC | |
by at2marty (Novice) on Sep 16, 2011 at 00:12 UTC | |
by toolic (Bishop) on Sep 16, 2011 at 01:17 UTC | |
by keszler (Priest) on Sep 16, 2011 at 01:30 UTC | |
|
Re: How To Read Hosts File Into a Hash
by jwkrahn (Abbot) on Sep 16, 2011 at 00:58 UTC |