Perl 搜索包含在数组中的字符串 [英] Perl searching for string contained in array

查看:77
本文介绍了Perl 搜索包含在数组中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下值的数组:

I have an array with the following values:

push @fruitArray, "apple|0";
push @fruitArray, "apple|1";
push @fruitArray, "pear|0";
push @fruitArray, "pear|0";

我想知道这个数组中是否存在字符串apple"(忽略|0"|1")

I want to find out if the string "apple" exists in this array (ignoring the "|0" "|1")

我正在使用:

$fruit = 'apple';
if( $fruit ~~ @fruitArray ){ print "I found apple"; }

这不起作用.

推荐答案

我 - 就像 @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;
      

      这篇关于Perl 搜索包含在数组中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆