Method 2 - Better approachuse 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
Updated: added the 3rd method after seen jonadab's suggestion. Here's my solution of capturing a real host file.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
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
$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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |