Re: How to conditionally substitute in files?
[email protected] ("John W. Krahn")
| Newsgroups | perl.beginners |
|---|---|
| Message-ID | <[email protected]> |
Siegfried Heintze (Aditi) wrote:
> This works:
>
> perl -i.bak -ple "s/class/xybpublicabc/g" Migration.cs
>
> However, when there are no matches, it still creates a new .bak file.
>
> How can we not change the date time on a file if there are no substitutions make?
You have to code it that way explicitly yourself, something like (UNTESTED):
my $file = 'Migration.cs';
open my $IN, '<', $file or die "Cannot open '$file' $!";
open my $OUT, '>', "$file.new" or die "Cannot open '$file.new' $!";
my $changed;
while ( <$IN> ) {
$changed += s/class/xybpublicabc/g;
print $OUT;
}
close $OUT;
close $IN;
if ( $changed ) {
rename $file, "$file.bak" or die "Cannot rename '$file' $!";
rename "$file.new", $file or die "Cannot rename '$file.new' $!";
else {
unlink "$file.new" or die "Cannot unlink '$file.new' $!";
}
__END__
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall