Searching

Sorting's easy; there's a function for it. Searching a list for a particular element—or for a part of an element—isn't quite so straightforward. Searching is one of those things where there is definitely more than one way to do it. Given a list of strings and a search string, you could, for example, simply iterate over the list with a foreach loop and test each element against the string, like this:

chomp($key = <STDIN>);  # thing to look for
foreach $el (@strings) {
   if ($key eq $el) {
      $found = 1;
   }
}

If the thing you were searching for can be a substring of an element in the list, you could use the index function to search for the substring in the string. The index function returns the position of the substring in the string, if it's ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.