Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 计算一个单词在一个文件中出现的次数以及出现的行数?_Regex_Perl - Fatal编程技术网

Regex 计算一个单词在一个文件中出现的次数以及出现的行数?

Regex 计算一个单词在一个文件中出现的次数以及出现的行数?,regex,perl,Regex,Perl,让我们在文本文件“script.txt”中解释一下,我必须找到“foo”这个词出现了多少次,在哪些行中,我必须列出这些行。尝试如下 my $total; my $lines; open my $fh,"<","file.txt"; while (<DATA>) { if(my $ech_count = () = /\bfoo\b/g) { $total+=$ech_count; $lines.=$.."\n"; } }

让我们在文本文件“script.txt”中解释一下,我必须找到“foo”这个词出现了多少次,在哪些行中,我必须列出这些行。

尝试如下

my $total;
my $lines;
open my $fh,"<","file.txt";
while (<DATA>)
{
    if(my $ech_count = () = /\bfoo\b/g)
    {
        $total+=$ech_count;
        $lines.=$.."\n";
    }

}
print " Total count : $total\nLines are: \n $lines";
my$total;
我的$line;
打开我的$fh,“请尝试以下操作:

use strict;
use warnings;

my @lines = <DATA>;
my ($word_count, $total) = '';
foreach my $single(@lines)
{
    if($single=~m/\bfoo\b/g)
    {
        $word_count = $single=~s/\bfoo\b/$&/g;
        print "Line Matched: $single\n";
        $total = $total + $word_count;
    }
}
print "Foo Count: $total\n";   
使用严格;
使用警告;
我的@lines=;
我的($word\u count,$total)='';
foreach我的$single(@行)
{
如果($single=~m/\bfoo\b/g)
{
$word\u count=$single=~s/\bfoo\b/$&/g;
打印“行匹配:$single\n”;
$total=$total+$word\u count;
}
}
打印“Foo Count:$total\n”;
my$val=;chomp($val);my$cnt=0;open(HNDL,$val)| | die“错误的文件名”;while($val=){while($val=~/\bis\b/ig){++$cnt;}}print“is”的实例数:$cnt\n\n;print“$:$val\n”;close(HNDL);