Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Inline Replacement in a Perl Script

Tags:

perl

I am trying to write a perl script with inline replacement. I have found this script example to do it, but not sure how to use it as im not sure how to specify the file and handler?

$^I = '.bak'  # Call for in-place editing; make backups with a .bak suffix

while (<>) 
{
  s/foo/bar/
  print;
}
like image 540
ard Avatar asked Dec 01 '25 05:12

ard


1 Answers

The <> is a special file handle.

The special file handle: <>

Like the default variable, the special file handle -- written as <> is a short cut in the language added to make programs easier to write. The special file handle treats all command line arguments as file names, and opens each in turn. If there are no command line arguments then it opens and reads from STDIN. As per the UNIX convention, if "-" is given as a command line argument it opens STDIN in place of a file.

Source

Setting the $^I variable enables in-place editing - in other words the file is modified directly.

To use this script you can for example do this:

perl yourscript.pl somefile.txt
like image 121
Mark Byers Avatar answered Dec 03 '25 22:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!