我是Perl的初学者,正在使用Strawberry-Perl,
我编写了一个Perl脚本来查找文本文件中的特定字符串,
============================
(文件名:sample.txt)
============================
这是我的代码,
#!
my @eatables = ("fruit", "meat", "vegetable");
open(FH, "<sample.txt") or die "Can't open sample.txt: $!";
sub main(){
while(my $line = <FH>){
foreach(@eatables){
if($line =~ m/$_/){
print "found: $_ at line $.\n";
}
}
}
close(FH);
}
main();
1;
我收到以下照片,
found: fruit at line 1
found: fruit at line 2
found: vegetable at line 3
found: fruit at line 4
found: vegetable at line 5
found: vegetable at line 6
found: fruit at line 7
found: vegetable at line 8
found: fruit at line 9
found: fruit at line 10
这里我需要在我的控制台中打印“not found:meat”,因为sample.txt中的字符串“meat”不可用。我可以用什么来做这件事?或者我是否需要修改我的搜索逻辑?请帮忙。
提前致谢,
此致 Ramkumar KA
答案 0 :(得分:0)
my @eatables = ("fruit", "meat", "vegetable");
open(FH, "<sample.txt") or die "Can't open sample.txt: $!";
sub main(){
my $hash = {"fruit" => 0, "meat" => 0, "vegetable" => 0};
while(my $line = <FH>){
foreach(@eatables){
if($line =~ m/$_/){
print "found: $_ at line $.\n";
$hash->{$_}++;
}
}
}
foreach(keys%{$hash}) {
print "not found : $_" if $hash->{$_} == 0 ;
}
close(FH);
}
通过这种方式,您可以知道每个字符串出现的次数。
答案 1 :(得分:0)
#!/usr/bin/perl
use strict;
my @eatables = ("fruit", "meat", "vegetable");
my ($combined_search, $not_found) = (join("|",@eatables)) x 2;
sub main() {
while(my $line = <STDIN>) {
$line =~ /($combined_search)/ ;
print "\nFound: $1";
$not_found =~ s/$1//g;
}
}
main();
print "Not found: $not_found";