user3387320
user3387320

Reputation: 7

how can i modify a text file by perl

I want to make 'find/change' function.

  1. open original file.
  2. change some words through using s/ / / or tr/ / / but it's not working, i think.

    open(TXT, ">>text.txt");
    my $str = <TXT>;
    $str =~ s/'a'/'b'/;
    print TXT $str;
    

Upvotes: 0

Views: 2128

Answers (2)

Filippo Lauria
Filippo Lauria

Reputation: 2064

Look at this example:

 ...
open RH, "text.txt" or die $!;
chomp(my @lines = <RH>);
close RH;

open WH, ">text.txt" or die $!;
foreach my $line (@lines) {
  $line =~ s/'a'/'b'/;
  print WH "$line\n";
}
close WH;
 ...

Upvotes: -1

Borodin
Borodin

Reputation: 126722

Your program opens a file for append, so you won't be able to read from it and the line my $str = <TXT> will set $str to undef.

You can write this as a one-line console command, using

perl -i.backup -pe"s/'a'/'b'/g" myfile

which substitutes the string 'a' (including the quotes) with the string 'b' throughout the file, and saves a backup to myfile.backup

Or you can write a program like this

use strict;
use warnings;

open my $fh, '<', 'myfile' or die qq{Unable to open input file: $!};

while (<$fh>) {
  s/'a'/'b'/g;
  print $_;
}

which leaves the input file intact and sends the modified data to STDOUT, so it can be redirected to a new file with the command

perl modify.pl myfile > myfile.new

Upvotes: 2

Related Questions