Perl (Scripting) - Do something end of line ($)

by
Jeremy Canfield |
Updated: December 28 2021
| Perl (Scripting) articles
The $ character is used to do something from the end of a line. For example, let's say the $foo variable contains "Hello".
my $foo = "Hello";
The $ character can be used to append to the $foo variable. In this example, "World" is appended to the end of the $foo variable.
$foo =~ s|$| World|;
Printing $foo . . .
print $foo;
Should return "Hello World".
Hello World
The $ character can also be used to replace. In this example, the $foo variable will be replaced to be "Hello Earth".
#!/usr/bin/perl
use strict;
use warning;
my $foo = "Hello World";
$foo =~ s|World$|Earth|;
Often, a variable may contain multiple different strings. Let's say sometimes the $foo variable will end with "World" and sometimes "Earth". Here is how you would update the $foo variable to end with "bar" instead of World or Earth.
#!/usr/bin/perl
use strict;
use warning;
my $foo = "Hello World";
$foo =~ s|(World|Earth)$|bar|;
Did you find this article helpful?
If so, consider buying me a coffee over at