Reputation: 7
I want to make 'find/change' function.
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
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
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