Tassilo Von Parseval wrote:
> On Mon, Jun 09, 2003 at 02:46:48AM -0500 christopher j bottaro wrote:
>
> > what is the easiest way to replace text in a file? say i have file blah.txt
> > and i want to replace some regular expression found in that file with
> > something. also, i want to do this from within the perl program, not by
> > invoking perl with the -e option.
>
> You can use the same underlying technique from within a Perl script. You
> have to set two special variables accordingly and Perl can even do an
> inplace-edit:
>
> local $^I = 1; # enable inplace editing
> local @ARGV = "blah.txt"; # make it accessible with <>
> while (<>) {
> s/blabla/BLABLA/;
> print;
> }
The value of $^I is the string to be appended to the backup copy of
the original file. The above will edit 'blah.txt' and rename the original
file to 'blah.txt1'.
> This however might not work on Windows due to some limitations concerning
> open files.
As far as I know this is fine on all systems, including Windows. It will fail
only if $^I is the empty string, which implies editing without a backup and
is not supported by Windows. To disable editing in place $^I must be set to
'undef'. A 'false' value will not do.
> So if the above is no option for you, you have to do it manually:
>
> open IN, "blah.txt" or die $!;
> open OUT, "blah.txt.tmp" or die $!;
open OUT, "> blah.txt.tmp" or die $!;
> while (<IN>) {
> s/blabla/BLABLA/;
> print OUT;
> }
>
> close IN;
> close OUT;
>
> rename "blah.txt.tmp", "blah.txt" or die "Renaming: $!";
Cheers,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]