On 11/14/2012 12:05 PM, jet speed wrote:
Hi
Is there a way, i can build an %hash from a file as Input. Appreciate you
help with this.
file.txt
----------------
22:5a => 10.00.00.00.aa.56.9b.7a
32:9c => 10.00.00.00.aa.46.9b.33
a2:cc=> 10.00.00.00.aa.5a.9b.63
Thanks
Sj
J.S.:
Thought of two ways to do it, right off the top of my head. First way:
#!/usr/bin/perl
open my $fh, "<", "file.txt" or
die "Error opening file.txt for input: $!";
my %hash;
while(<$fh>) {
chomp;
my ($k, $v) = m/(\S+) *\=\> *(.*)$/;
$hash{$k} = $v;
}
print "$_ : $hash{$_}\n" foreach keys %hash;
That method extracts the key and value out of the input lines, and
builds up the hash. If you are wanting to *REALLY* use those fat commas
in the file, then you might try something like this:
#!/usr/bin/perl
open my $fh, "<", "file.txt" or
die "Error opening file.txt for input: $!";
my %hash;
my @lines = (<$fh>);
chomp @lines;
s/(\S+) *\=\> *(.*)$/\'$1\' \=\> \'$2\'/ foreach @lines;
my $lines = join "," , @lines;
%hash = eval "( $lines )";
print "$_ : $hash{$_}\n" foreach keys %hash;
Personally, I like the first one better.
Nathan