Scenario: You have this data structure X, and need to know if string Y might be hiding in there somewhere.
This happens all the time, and is probably what you will keep on repeating over and over again, for different purposes.
Let’s take a look at how we can do this in some interesting ways.
There Is More Than One Way To Do It
If you simply need to know if an element exists, you can use the smart-match operator introduced in Perl 5.10:
If you need to grab the first element that matches evaluated pattern, you can use the ‘first’ function from the core List::Util module:
You are not limited to regular expressions, either:
The first function works on hashes as well, and maybe it’s first here were we’ll see how useful it can be.
Instead of manually looping through the hash if you’re interested in the key for a specific value, you can do it like this:
So the first function is pretty useful, but it wont do any good if we’re interested in several values. Here is where grep comes in to play.
Those that are familiar with the grep command from Gnu/Linux and UNIX environments are probably using it everyday, and for good reason.
grep() in Perl is not the same, but similar in spirit. Let’s take a look:
Sidenote: \d matches a single character that’s considered to be a digit. Digits are not necessarily 0-9 - it depends on the encoding of the source string and the LOCALE that’s in effect. It’ll happily match indian devanagardi numerals as well; therefore it might be a good idea to use [0-9] if you suspect that you might deal with more exotic things.