简体   繁体   中英

Substitute Text with RegEX in external file Perl

I am trying to have a script that will update a variable in an input file. The RegEx matches but it does not perform the substitution. What am I doing wrong.

sub updateInputDeck {
my $powerLevel = shift;
my $file = $outputFiles{input};
open INPUTFILE,"<",$file or die "Cannot open file $file $!\n";
while (<INPUTFILE>) {
    if (s/((?<=\s{3}RP\s{2}=\s{2})\d+)/$powerLevel/) {
        print $_;
        print "Updating Input File for Power Level: $powerLevel";
     }
}
close INPUTFILE;
}

UPDATE

I am trying to update the file pointed to in the filehandle. Can I only do this via a print statement. If that is the case I just want to reprint that one line. Is that possible?

You can use perl's in-place editing :

sub updateInputDeck {
    my $powerLevel = shift;
    my $file = $outputFiles{input};

    local @ARGV = ($file);
    local $^I = '.bac';
    while( <> ){
        s/((?<=\s{3}RP\s{2}=\s{2})\d+)/$powerLevel/;
        print;
    }

    #unlink "$file$^I" or die "Can't delete backup";

    return;
}

Also note, that your use of a global $outputFiles{input} as a parameter to your function is a bad style practice. Instead pass it as a parameter to your function as well.

I think you have to do it in 2 passes. First read the whole file into an array, edit it locally and write the whole thing back out, overwriting the original file.

open INPUTFILE,"<$file" or die "Cannot open file $file $!\n";
my @lines = <INPUTFILE>; # Read in entire file.
close INPUTFILE;

open INPUTFILE,">$file" or die "Cannot open file $file $!\n";
foreach $line (@lines) {
  $line =~ s/((?<=\s{3}RP\s{2}=\s{2})\d+)/$powerLevel/;
  print INPUTFILE $line;
}
close INPUTFILE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM