Bootstrap FreeKB - Perl (Scripting) - Replace element in array (map)
Perl (Scripting) - Replace element in array (map)

Updated:   |  Perl (Scripting) articles

Let's say you have an array of fruit.

my @fruit = qw(apple banana orange pineapple);

 

The map function can be used to do a replacement on the array. In this example, the text "apple" is replaced with "EXAMPLE".

map { s/apple/EXAMPLE/g } @fruit;

 

The array will now contain these values. Notice that "apple" in "pineapple" was replaced.

EXAMPLE
banana
orange
pineEXAMPLE

 


Forward slash vs pipe

The map function can use either forward slash or pipe. For example, both of these formats will replace "apple" with "EXAMPLE".

map { s/apple/EXAMPLE/g } @fruit;
map { s|apple|EXAMPLE|g } @fruit;

 

Let's say one of the lines in the array contains forward slashes.

/path/to/directory

 

In this situation, it makes sense to use pipe's in the map function.

map { s|/path/to/directory|EXAMPLE|g } @array;

 


Wildcards

Wildcard characters will almost always cause the replacement to not work as expected. If there is a wildcard character in the old or new string, refer to this article for a list of different techniques you can use to handle the wildcard character.




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