in reply to Re: How To Read Hosts File Into a Hash
in thread How To Read Hosts File Into a Hash

Thank you for your reply. I changed my code to the following.

#!/usr/bin/perl -w use strict; my $hostfile = "/etc/hosts"; my %hosts = (); open FILE, "<", "$hostfile" || die "Cannot open $hostfile $!"; while (<FILE>) { next if /^\s*#/ ; # skip comments chomp; my ($key, $value) = split (" ", $_); $hosts{$key} = $value; } close FILE;

The output is as follows.

Use of uninitialized value $key in hash element at hash.pl line 14, <F +ILE> line 3. Use of uninitialized value $key in hash element at hash.pl line 14, <F +ILE> line 11.

Why do I get the "uninitialized error" for $key?

Replies are listed 'Best First'.
Re^3: How To Read Hosts File Into a Hash
by toolic (Bishop) on Sep 16, 2011 at 01:17 UTC
    Why do I get the "uninitialized error" for $key?
    My guess is your input file has a blank line:
    while (<FILE>) { next if /^\s*#/ ; # skip comments next unless /\S/; # skip blank lines chomp; my ($key, $value) = split; $hosts{$key} = $value; }
    See perlre
Re^3: How To Read Hosts File Into a Hash
by keszler (Priest) on Sep 16, 2011 at 01:30 UTC

    Your /etc/hosts file lines 3 and 11 have zero or more white space characters and nothing else. You should skip those:

    while (<FILE>) { next if /\A\s*\z/ ; # skip blank lines next if /^\s*#/ ; # skip comments

    Or combine the regexes:

    next if /\A\s*(?:#|\z)/ ; skip comments and blank lines