Or you could write a one-liner to transform the input file into a hash.

Method 1 - (map with 'short-circuit', now handles empty lines)
use strict; use Data::Dumper; # Uh, well spotted, typo fixed with the extra + # which would have no effect anyway. :-) # ysth suggested that putting () in map shortcircuts # empty lines. It worked. Thanks. :-) # Wow, even better, dropped that testing bit. #my %hostlist = map { /^(\w+)\s(.*)/?($1,$2):() } (<DATA>); my %hostlist = map { /^(\w+)\s(.*)/ } (<DATA>); print Dumper(\%hostlist); __DATA__ host1 1.1.1.1 host2 1.2.3.5
Method 2 - Better approach
use strict; use Data::Dumper; my %hostlist; { local $/; %hostlist = <DATA> =~ /^(\w+)\s(.*)/gm; } print Dumper(\%hostlist); __DATA__ host1 1.1.1.1 host2 1.2.3.5
Updated: added the 3rd method after seen jonadab's suggestion. Here's my solution of capturing a real host file.

Method 3 - Capture from the /etc/host file
use strict; use Data::Dumper; my %hosts; while (<DATA>) { next if /^\s*(?:#|$)/; # ignore comments and empty lines /^([^\s#]+)\s+(.*)/; # capture ip address and names $hosts{$_} = $1 foreach split /\s+/, $2; } print Dumper(\%hosts); __DATA__ # IP Masq gateway: 192.168.0.80 pedestrian # Primary desktop: 192.168.0.82 raptor1 # Family PC upstairs: 192.168.0.84 trex tyrannosaur family # Domain servers: 205.212.123.10 dns1 brutus 208.140.2.15 dns2 156.63.130.100 dns3 cherokee
And the output -
$VAR1 = { 'dns3' => '156.63.130.100', 'brutus' => '205.212.123.10', 'raptor1' => '192.168.0.82', 'trex' => '192.168.0.84', 'cherokee' => '156.63.130.100', 'dns1' => '205.212.123.10', 'tyrannosaur' => '192.168.0.84', 'dns2' => '208.140.2.15', 'family' => '192.168.0.84', 'pedestrian' => '192.168.0.80' };

In reply to Re: newbie hasher by Roger
in thread newbie hasher by prodevel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.