Vidisha
Vidisha

Reputation: 63

How to print the output to same file you are reading from in perl?

I have a perl script which reads a file, changes the required thing and then prints the output of the file on the console. I want the output to be updated in the same file from where it is picking the data.

How can this be done?

Upvotes: 0

Views: 139

Answers (1)

choroba
choroba

Reputation: 242218

You can use the -i switch, or the $^I special variable.

perl -i.backup -pe 's/change me/something else/'

or

#!/usr/bin/perl
use warnings;
use strict;

$^I = '.backup';
while (<>) {
    ...
    print;
}

Note that it only works for the special file handle *ARGV used by the diamond operator. It creates a new file behind the scenes, anyway.

See perlrun and perlvar.

Upvotes: 3

Related Questions