
Let's say foo.txt contains Hello World.
Hello World
There are two ways in which Perl can replace Hello World with some other value. One way is to use Perl on the command line and the other is withing a Perl script.
Command Line
In this example, the text "Hello" will be replaced with the text "Hi". It is also important to recognize that when the -i options is not used, the text in the file will not be changed. Instead, the result will simply be displayed in the terminal.
perl -p -e 's/Hello/Hi/' foo.txt
The -i option will actually change the content of the file.
perl -pi -e 's/Hello/Hi/' foo.txt
Script
Let's say the $foo variable contains a value of Hello World.
my $foo = "Hello World";
Within a Perl script, the =~ operator is used to replace data. In this example, the $foo variable is updated so that "Hello" will be replaced with the "Hi".
$foo =~ 's/Hello/Hi/'
Did you find this article helpful?
If so, consider buying me a coffee over at