Perl (Scripting) - Do something beginning of line (^)

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