检查值存在于perl数组和子串

时间:2017-05-30 10:31:37

标签: arrays excel perl

我有一个包含原始数据的数组和excel文件中的列,我需要将excel列与数组进行比较并找到匹配项。

我需要的是走路应该跟我一起走路等等,有什么方法可以做到。

can i compare individual string with complete array i am comparing excel row with array using the following way description variable contains string to match with @steps_name array

my @steps_name=("1-2 Steps", "5-7 Steps", "8-10 Steps", "11-15 Steps");

foreach $sheet (@{$workbook->{Worksheet}}) {

       foreach $col ($sheet->{MinCol} .. $sheet->{MaxCol})
       {          
                if ($sheet->{Cells}[0][$col]->{Val} eq "DESCRIPTION") 
               {
                    $description = $col;                    
               }                 
       }



    foreach $row ($sheet->{MinRow}+1 .. 50) 
     {         
       my $db_description = $sheet->{Cells}[$row][$description]->{Val};

        my $needle_regex = quotemeta $db_description;    

     if (grep { /(?i)\Q$db_description\E/ } @steps_name) 
                {
           print "<br><h1>Element '$db_description' found </h1></br>" ;
                }

                else
                {
                    print "<br>$db_description not found </br>"
                }

      }
    }

提前致谢。

1 个答案:

答案 0 :(得分:1)

将列表分配给标量($db_description)没有任何意义。此外,eq测试字符串相等性,并且您所比较的字符串都不会相等。您可能希望使用正则表达式来查看 needle 是否与 haystacks 的一部分匹配:

use strict;
use warnings;

my @needles   = ("walk", "run", "dance", "catch");
my @haystacks = ("walk with me", "come and run", "catch the ball");

for my $needle (@needles) {
    my $found;

    for my $haystack (@haystacks) {
        if ($haystack =~ /\Q$needle\E/) {
            print "Found [$needle] in [$haystack]\n";
            $found++;
        }
    }

    if (!$found) {
        print "Couldn't find [$needle] anywhere!\n";
    }
}

这可以缩短为:

for my $needle (@needles) {
    if (grep { /\Q$needle\E/ } @haystacks) {
        print "Found [$needle]\n";
    } else {
        print "Couldn't find [$needle] anywhere!\n";
    }
}