Bootstrap FreeKB - Perl (Scripting) - Replace values in a variable (=~)
Perl (Scripting) - Replace values in a variable (=~)

Updated:   |  Perl (Scripting) articles

In this example, the $foo variable contains a value of bar.

my $foo = "bar";

 

The =~ operator is used to replace a value in a variable. In this example, bar is replaced with Hello World. The $foo variable will now contain a value of "Hello World". You can use either forward slash or pipe.

$foo =~ s/bar/Hello World/g;
$foo =~ s|bar|Hello World|g;

 


Array

Let's say you have the following script.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @fruits = qw(apple banana orange pear);

print Dumper \@fruits;

foreach my $fruit (@fruits) {
  $fruit =~ s|apple|peach|;
}

print Dumper \@fruits;

 

Running this script will return the following which shows that while looping over the @fruits array, modifying the $fruit variable also updates the @fruits array.

$VAR1 = [
          'apple',
          'banana',
          'orange',
          'pear'
        ];
$VAR1 = [
          'peach',
          'banana',
          'orange',
          'pear'
        ]

 

If you want to avoid the @fruits array from being updated, you can apply the modification to some other variable, such as $inner.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @fruits = qw(apple banana orange pear);

print Dumper \@fruits;

foreach my $fruit (@fruits) {
  my $inner = $fruit;
  $inner =~ s|apple|peach|;
}

print Dumper \@fruits;

 


( and ) characters

The ( and ) characters will need to be escaped. For example, let's say you want to replace (foo) with (bar).

$foo =~ s|\(foo\)|\(bar\)|g;

 




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 ec596a in the box below so that we can be sure you are a human.