How to use Perl to perform computational-based lookups?

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!

+3
source share
3
s/(-*\d+.\d+)/$scalingFactor*$1/ge

( e )

+4

, . $^I, Perl. ( $^I . "perlvar", man- "perlrun" -i, .)

use strict;  # Always.

sub scale_numbers_in_file_by_factor {
    my ($path, $scaling_factor) = @_;
    local @ARGV = ($path);
    local $^I = '.bak';
    while (<>) {
        s/ ( -? \d+ \. \d+ ) / $scaling_factor * $1 /gex;
        print;
    }
}

scale_numbers_in_file_by_factor('my-file.txt', .1);

'.bak' . '.bak' '' , .

, , . , . , , -? , -*, . , .

+3

Open the file descriptor called OUTPUT and print OUTPUT $ new

-1
source

All Articles