且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Perl 搜索包含在数组中的字符串

更新时间:2023-11-06 23:02:58

我 - 就像 @Borodin 建议的那样 - 只会使用 grep():

I - like @Borodin suggests, too - would simply use grep():

$fruit = 'apple';
if (grep(/^\Q$fruit\E\|/, @fruitArray)) { print "I found apple"; }

输出:

I found apple

  • \Q...\E 将您的字符串转换为正则表达式.
  • 查找 | 可防止找到名称以您要查找的水果名称开头的水果.
    • \Q...\E converts your string into a regex pattern.
    • Looking for the | prevents finding a fruit whose name starts with the name of the fruit for which you are looking.
    • 简单有效... :-)

      Simple and effective... :-)

      更新:从数组中删除元素:

$fruit = 'apple';
@fruitsArrayWithoutApples = grep ! /^\Q$fruit\E|/, @fruitArray;