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;
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
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;
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.