Find string in array in perl

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Find string in array in perl

There are cases in your projects where you will most likely want to search an array for a specific element or string. There is no function like how it is in PHP for example that could do this automatically, but there is one core function that can be used to search a specific string in anything really, be it array or string.


We have a little array with 5 elements and we want to proceed further in our application only if a specific needle is found in our array.

So this is our little array.


To get around this, we will use the core function in perl named grep which we will use to find a string in our little array.


The result would print the string within the if clause. Basically that’s how you check. Of course you can also make it so that if the needle does not exist in our array, to proceed further, for example:

In this example we add “Bob” to our array list, but first checking if it exists, if not, proceed and add the element to our little array.

On the later part we just parse array and print the elements one per line.


That’s it for now, see you in our next tutorial!

Request an article ←