How do I search a Perl array for a matching string?

后端 未结 7 1685
一向
一向 2020-12-04 15:37

What is the smartest way of searching through an array of strings for a matching string in Perl?

One caveat, I would like the search to be case-insensitive

s

7条回答
  •  醉梦人生
    2020-12-04 16:27

    It depends on what you want the search to do:

    • if you want to find all matches, use the built-in grep:

      my @matches = grep { /pattern/ } @list_of_strings;
      
    • if you want to find the first match, use first in List::Util:

      use List::Util 'first';  
      my $match = first { /pattern/ } @list_of_strings;
      
    • if you want to find the count of all matches, use true in List::MoreUtils:

      use List::MoreUtils 'true';
      my $count = true { /pattern/ } @list_of_strings;
      
    • if you want to know the index of the first match, use first_index in List::MoreUtils:

      use List::MoreUtils 'first_index'; 
      my $index = first_index { /pattern/ } @list_of_strings;
      
    • if you want to simply know if there was a match, but you don't care which element it was or its value, use any in List::Util:

      use List::Util 1.33 'any';
      my $match_found = any { /pattern/ } @list_of_strings;
      

    All these examples do similar things at their core, but their implementations have been heavily optimized to be fast, and will be faster than any pure-perl implementation that you might write yourself with grep, map or a for loop.


    Note that the algorithm for doing the looping is a separate issue than performing the individual matches. To match a string case-insensitively, you can simply use the i flag in the pattern: /pattern/i. You should definitely read through perldoc perlre if you have not previously done so.

提交回复
热议问题