I am trying to write a perl script to search in a text file, search for all decimal numbers and change them using some scaling factor. So far, I have been able to extract regular expression numbers:
open(INPUT, $inputPath) or die "$inputPath cannot be opened.";
while ($thisLine = <INPUT>) {
while ($thisLine =~ m/(-*\d+\.\d+)/g) {
if(defined($1)) {
$new = $scalingFactor*$1;
print $new."\n";
}
}
}
close (INPUT);
However, I still do not understand how to insert new values into a file. I tried using s/(-*\d+.\d+)/$scalingFactor*$1/gsubstitution, but of course this inserted a string representation $scalingFactorinstead of evaluating an expression.
I am new to perl, so any help would be greatly appreciated. Thanks in advance,
Dan
Edit: Solution (based on Roman answer)
while ($thisLine = <INPUT>) {
$thisLine =~ s/(-*\d+\.\d+)/$scalingFactor*$1/ge;
prinf OUTPUT $thisLine;
}
Alternatively, Sean's solution also worked great for me. Thanks everyone!
source
share