It looks like you want in-place editing magic. The easiest way to get this is to use $^I
with the magic of @ARGV
plus <>
(look for null filehandle in the I/O Operators section):
#!/usr/bin/perl
use strict;
use warnings;
my $find = qr/\s{6}seqfile\s=\sinfile/;
my $replace = ' seqfile = infil2';
@ARGV = ("/home/shubhi/Desktop/pamlrun/test");
$^I = ".bak"; #safe the old files as file.bak
while (<>) {
s/$find/$replace/g;
print;
}
Also, given the nature of your regex, it looks like you probably want [ ]
(match a space) or \t
(match a tab) not \s
. \s
will match tabs, spaces, and other whitespace characters.
You can also use Tie::File
, but it doesn't seem to provide a backup capability:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
my $find = qr/\s{6}seqfile\s=\sinfile/;
my $replace = ' seqfile = infil2';
tie my @lines, "Tie::File", "testdata"
or die "could not open file: $!";
for my $line (@lines) {
$line =~ s/$find/$replace/g;
}
Of course, you could roll your own backups with File::Copy
:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
use File::Copy;
my $find = qr/\s{6}seqfile\s=\sinfile/;
my $replace = ' seqfile = infil2';
copy "testdata", "testdata.bak"
or die "could not backup file: $!";
tie my @lines, "Tie::File", "testdata"
or die "could not open file: $!";
for my $line (@lines) {
$line =~ s/$find/$replace/g;
}
I would also be remiss if I did not point out that this is basically a one-liner:
perl -pi.bak -e 's/\s{6}seqfile\s=\sinfile/ seqfile = infil2/' testdata
This can be shortened further with Perl 5.10 by taking advantage of \K
(zero-width positive look-behind):
perl -pi.bak -e 's/\s{6}seqfile\s=\s\Kinfile/infil2/' testdata