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

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;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |