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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 8df5bb in the box below so that we can be sure you are a human.