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.



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.



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

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



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


Add a Comment

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