Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: In place search and replace with a hash

by eyepopslikeamosquito (Archbishop)
on Dec 28, 2014 at 06:21 UTC ( [id://1111538]=note: print w/replies, xml ) Need Help??


in reply to In place search and replace with a hash

I don't like your code to populate your hash, namely:

my ($key, $value) = split /\s/, $line; next LINE if not $key; $hash{$key} = $value; chomp (%hash);
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.

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
    ... the doco for chomp does not mention applying it to a hash ...

    chomp sez: If VARIABLE is a hash, it chomps the hash's values, but not its keys...


    Give a man a fish:   <%-(-(-(-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1111538]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-19 18:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found