RE: How to conditionally substitute in files?

[email protected] ("Siegfried Heintze (Aditi)")
Newsgroups perl.beginners
Message-ID <EB070C90E3B48C4F97C7AC252BACE9E72326A6B558@NA-EXMSG-C125.redmond.corp.microsoft.com>
Thanks John!
I to edit it a little but it works!

Can someone explain to why I have to remove the $ from $IN and $OUT and remove the "my" in "my $IN" and "my $OUT" to make it work?
Thanks,
Siegfried

-----Original Message-----
From: John W. Krahn [mailto:[email protected]]
Sent: Thursday, June 12, 2008 1:08 PM
To: Perl Beginners
Subject: Re: How to conditionally substitute in files?

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

--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.