in reply to In place search and replace with a hash
I don't like your code to populate your hash, namely:
Though the chomp(%hash) kinda "works", the doco for chomp does not mention applying it to a hash and accordingly, I feel this code is unclear. Update: Whoops, the chomp doco does indeed mention applying chomp to a hash, as pointed out below. Thanks AnomalousMonk.my ($key, $value) = split /\s/, $line; next LINE if not $key; $hash{$key} = $value; chomp (%hash);
I would do it something like this:
use strict; use warnings; use Data::Dumper; my %hash; open my $fh, '<', 'hash.txt' or die "Can't open file $!"; while (my $line = <$fh>) { chomp $line; # remove trailing newline $line =~ s/^\s+//; # optional: remove leading whitespa +ce $line =~ s/\s+$//; # optional: remove trailing whitesp +ace next unless length($line); # ignore blank lines next if $line =~ /^#/; # optional: to allow comment lines # Format: key whitespace value (value can contain whitespace) my ($key, $value) = split ' ', $line, 2; defined($value) or die "error: no value for '$key'"; $hash{$key} = $value; } close $fh; print Dumper(\%hash);
You might further want to consider what will happen if your key contains regex metachars (e.g. abc.xyz). Maybe this can't happen for your data ... but if it does, your regex may be incorrect (could use /\Q$key\E/ to escape metachars, if required by your data).
Re safely editing a file in place, see:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: In place search and replace with a hash
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 18:21 UTC |