为什么需要这行代码?

时间:2018-02-26 18:08:14

标签: perl

这是代码

#!/usr/bin/perl
my ($items,
@aryitems,
@aryitems2,
$search,
$size,
$num);
@aryitems2=('Chattahoochee','committee','bookkeeper'
,'millennium','cappuccino','Tattle','Illiad','Mississippi',
'Tennessee');
$size=@aryitems2;
print "The size of the array is $size\n";
print "Enter the string to search:";
chomp ($search=<STDIN>);
foreach (@aryitems2)
{
$num=0;
$pos=0;
print "The word is $_\n";
if (/$search/i)
{
    print "The pattern is '$search' and found in the word $_\n";
    while ($pos<(length $_) and $pos!=-1)
    {
        $pos=index ($_,$search,$pos);
        if ($pos!=-1)
        {
        $pos++;
        $num++;
        }
    }
    print "the number of times '$search' is found in this word is $num\n";
    }
    else
    {
    print "the pattern is '$search' and is not found in $_\n";
    }
}

我没有得到的部分是

$pos=index ($_,$search,$pos);

此代码的目的是什么?怎么没有

$pos=index ($_,$pos);

$pos=index($search,$pos);

等...

为什么需要它?

2 个答案:

答案 0 :(得分:2)

它在那里你可以计算在单词中找到模式的次数。它会跟踪先前找到的模式的位置,以便后续搜索能够进一步深入到单词中,并且不会发现已经发现的模式。

答案 1 :(得分:2)

你实在无法指定要查找的字符串($search)和要查找的字符串($_)。所以,至少需要

$pos = index($_, $search);

为什么没用过?因为它找到了第一场比赛,但目标是找到所有比赛。如果给出,index将开始查看第三个参数给出的位置,允许循环查找$search$_的每个实例。

请注意,由于使用的是$pos++;而不是$pos += length($search);,因此可以进行重叠匹配。例如,如果您在abab中搜索abababab,则您的算法会找到3个匹配而不是2个。

清理代码:

#!/usr/bin/perl
use strict;
use warnings qw( all );
use feature qw( say );

my @words = qw( Chattahoochee committee bookkeeper millennium cappuccino Tattle Illiad Mississippi Tennessee );

my ($search) = @ARGV
    or die("usage\n");

for my $word (@words) {
    my $count = 0;
    my $pos = 0;
    while (1) {
        $pos = index($word, $search, $pos);
        last if $pos < 0;

        ++$count;
        ++$pos;
    }

    say "$_ contains $count instances of $search";
}

使用匹配运算符代替index

#!/usr/bin/perl
use strict;
use warnings qw( all );
use feature qw( say );

my @words = qw( Chattahoochee committee bookkeeper millennium cappuccino Tattle Illiad Mississippi Tennessee );

my ($search) = @ARGV
    or die("usage\n");

for my $word (@words) {
    my $count = 0;
    ++$count while $word =~ /\Q$search/g;
    say "$_ contains $count instances of $search";
}