1

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!

2
  • You're always going to be reading the file into a string. Although, not necessarily the whole thing at once. A line at a time is fine. Commented Aug 31, 2012 at 0:01
  • I realize that. I'm just wanting to abstract it so I don't have to worry about it. I'm looking for a built-in way that PERL already has. Commented Aug 31, 2012 at 0:02

1 Answer 1

4

This is what Perl's -i ("inplace edit") switch is for:

$ perl -i.bak -pe 's/World/Earth/g' text_file.txt

EDIT: To incorporate this identical functionality into a larger Perl script:

{
    local $^I = '.bak';
    local @ARGV = ('text_file.txt');
    local $_;
    while (<>) {
        s/World/Earth/g;
        print;
    }
}

The $^I variable reflects the value of the -i command-line switch; here, it's being set manually. Also, @ARGV is 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 $^I and @ARGV, set with local, resume their original values afterwards; this may not be strictly necessary, depending on the rest of the program. I also localized $_ just to keep the while loop from clobbering the value it previously held; this also may not be necessary.

Note that you can use just -i instead of -i.bak from the command line if you want to avoid creating a backup file. The corresponding code would be $^I = "" instead of $^I = '.bak'.

Sign up to request clarification or add additional context in comments.

2 Comments

How do I add that to a PERL script? (Like I said, I'm pretty new)
In this case, s/World/Earth/g is the Perl script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.