user2812535
user2812535

Reputation: 13

changing file contents in perl - regex

I have a file (prac.txt) which contains something like this:

"line1"
"line2"
"Hello World"
"line3"

I want to read this entire file and replace "hello world" with "line 3". I wrote the code but it just hangs while execution. Can anyone guide me..? Looks like my regex needs some changes.

Here is my code:

my @tmp = ();

my $FILE;

open ( $FILE, '<', 'prac.txt') or die "Can't open prac.txt\n";

while($FILE) {


    my $cur_line = $_;

    if($cur_line =~ /\"Hello\"/){

        push(@tmp, " \" line 3\"; \n");

    }

    else {

        push(@tmp, $cur_line);

    }

}

close($FILE);

open ($FILE, '>', 'prac.txt') or die "Can't open file\n";

print FILE @tmp;

close($FILE);

Any help will be greatly appreciated. Thanks

Upvotes: 1

Views: 142

Answers (4)

Miller
Miller

Reputation: 35208

In a perl one-liner

perl -i -lpe '$_ = q{"Line 3"} if /"Hello World"/' prac.txt

Or expanded to a full script:

use strict;
use warnings;

local @ARGV = 'prac.txt';
local $^I = '.bak';

while (<>) {
    $_ = qq{"Line 3"\n} if /"Hello World"/;
    print;
}

# unlink "prac.txt$^I"; # Uncomment to delete backup.

Upvotes: 0

albe
albe

Reputation: 551

but this could be done much more easily:

perl -i -p -e 's/Hello World/line3/' prac.txt

Upvotes: 0

hmatt1
hmatt1

Reputation: 5159

There were a couple problems with the code. Here is a working version and I threw comments in where changes needed to be made.

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

my @tmp = ();

my $FILE;

open ( $FILE, '<', 'prac.txt') or die "Can't open prac.txt\n";

# You need to use the diamond operator `<>` around `$FILE` to read in the file.
while(<$FILE>) {


    my $cur_line = $_;

    # Make sure this regex matches your input file
    if($cur_line =~ /"Hello World"/){

        push(@tmp, " \" line 3\"; \n");

    }

    else {

        push(@tmp, $cur_line);

    }

}

close($FILE);

open ($FILE, '>', 'prac.txt') or die "Can't open file\n";

# You need a `$` in front of `FILE`
print $FILE @tmp;

close($FILE);

Also, I want to say good job using the correct 3 argument form of open and a lexical file handle.

Upvotes: 1

ooga
ooga

Reputation: 15511

You're missing the angle brackets around $FILE in your while. It should be

while (<$FILE>)

or perhaps

for my $cur_line (<$FILE>)

And you should include this at the top of your script for better error reporting:

use strict;
use warnings;

Upvotes: 0

Related Questions