Developer Developer - 5 months ago 7x
Perl Question

How to Edit a File Text in Perl

I have a file now in that i want to update the value of variable.How can we do this .
File Content:

NUM1 = 8
AMV1 = 8
AMV2 = 8
DEF2 = 8
DGF = 8

Now in this i want to change the value of
how can we do this in Perl.


You can do it directly from the command line with a one-liner:

perl -i~ -pe 's/^(\s*NUM1 )=.*/$1=NewValue/' config-file
  • -i~ changes the file "in place", leaving a backup with the tilde appended
  • -p reads the input line by line and prints it
  • s/// is a substitution
  • () create a capture group in a regex, the first capture group can be referenced from the replacement part as $1

In a script, you need to add replace -p with the actual code:

use warnings;
use strict;

while (<>) {
    s/^(\s*NUM1 )=.*/$1=NewValue/;

Save to update-config, run as update-config config-file > new-config.

Or, if you want to handle even the opening of the file yourself:

use warnings;
use strict;

my $filename = 'config-file';
my $newfile  = "$";
my $backup   = "$filename~";

open my $IN, '<', $filename or die $!;
open my $OUT, '>', $newfile or die $!;
while (<$IN>) {
    s/^(\s*NUM1 )=.*/$1=NewValue/;
    print {$OUT} $_;
close $OUT or die $!;
rename $filename, $backup or die $!;
rename $newfile, $filename or die $!;