How can I do regular expressions on a file instead of a string in perl?

Subaru

New member
I know you usually use regular expressions on strings with the =~ thingy. How can I do it on a text file though?

I mean, I want it to read the entire file as one string. How do I do that?

Thanks
 
You can't do it directly. You have to read the file into a string.

use strict;
use warnings;
use File::Slurp;
my $s = read_file(q{filename.txt});
$s =~ s/expression/replacement/g;
write_file(q{filename.txt}, $s);
__END__

Or you could try the command-line arguments:

perl -ibak -pe"s/expr/repl/g" filename.txt

But you have to be careful with quoting the characters in the regex, etc.
 
Back
Top