My Question: If I’m given C:\text_file.txt as a parameter on the command line when my PERL script is called and the text_file.txt contains the text “Hello World World World”, how do I replace all instances of “World” with “Earth”?
I’m new to PERL. I’m writing a script which accepts a parameter of a filepath. I want to do a find replace on the contents of the file. I know I could do something like this: $string =~ s/World/Earth/g; but I don’t want to read the file into a string if I can help it. Is there a way to do this directly on the file without reading it in as a string? Thanks!
This is what Perl’s
-i(“inplace edit”) switch is for:EDIT: To incorporate this identical functionality into a larger Perl script:
The
$^Ivariable reflects the value of the-icommand-line switch; here, it’s being set manually. Also,@ARGVis being manually set to the list of files that would ordinarily be taken from the command line. The whole thing is wrapped in a block so that$^Iand@ARGV, set withlocal, resume their original values afterwards; this may not be strictly necessary, depending on the rest of the program. I also localized$_just to keep thewhileloop from clobbering the value it previously held; this also may not be necessary.Note that you can use just
-iinstead of-i.bakfrom the command line if you want to avoid creating a backup file. The corresponding code would be$^I = ""instead of$^I = '.bak'.