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

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.

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


Web design by yours truely - me, myself, and I   |   |