in reply to In place search and replace with a hash
Some other thoughts on the OPed code.
my ($key, $value) = split /\s/, $line;
next LINE if not $key;
split returns its input string ($line in this case) if it cannot split according to the given pattern, so $key will almost always have a true value no matter what happens. Better to use
my ($k, $v) = split /\s/, $line;
next LINE if not defined $v;
I use defined to avoid false negatives from '0' and '' (the empty string), both of which evaluate as boolean false. I also use the variable names $k $v because I don't like using variaable names that are the same as Perl built-in functions, etc.
$hash{$key} = $value;
The hash %hash is presumably a package global. Better to use a pre-declared my lexical. (Better in general to avoid globals.)
chomp (%hash);
The chomp is done on all the values of the hash on every iteration through the while-loop. This does no harm, but needlessly burns cycles. chomp can be done just once on the hash after it is populated, i.e., after the while-loop.
Update: This code doesn't seem to really do anything:
To be sure, it opens a bunch of files and reads and potentially alters each line of each file... but then what? The (potentially) altered line is never written out to any file. Is this some sort of tied filehandle (see, e.g., Tie::File)? There's no indication of this if so. Also, I don't understand what you mean by "... I want to change the files in place." As I understand the phrase, this can be done only if the replacement strings are guaranteed to be exactly the same length as the sub-strings that are replaced. Again, no indication this is the case.@file_array =<*.txt> or die $!; foreach $file (@file_array) { open FH, "$file", or die $!; while (<FH>) { if (/(\S+):(\S+).*\n/) { s/$1/$hash{'$1'}_$2/g; } } close FH; }
Further Update: The process of "editing a file" (that has not been read into a tied array) on a line-by-line basis generally goes something like this (every step is assumed to be checked for success, i.e., it produces no error code):
Give a man a fish: <%-(-(-(-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: In place search and replace with a hash
by hkates (Novice) on Dec 28, 2014 at 03:29 UTC | |
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 03:52 UTC | |
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 03:39 UTC | |
|
Re^2: In place search and replace with a hash
by hkates (Novice) on Dec 28, 2014 at 03:54 UTC | |
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 04:29 UTC | |
by hkates (Novice) on Dec 28, 2014 at 04:42 UTC | |
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 05:33 UTC | |
by hkates (Novice) on Dec 28, 2014 at 21:22 UTC | |
by AnomalousMonk (Archbishop) on Dec 28, 2014 at 05:02 UTC |