perl 找出文本文件中不可用的字符串

nue99wik  于 2023-02-05  发布在  Perl
关注(0)|答案(2)|浏览(116)

我使用的是草莓Perl。
我编写了一个Perl脚本来查找文本文件中的特定字符串,

(file名称:样本. txt)
1.水果-苹果
1.水果-香蕉
1.蔬菜-马铃薯
1.水果-柑橘
1.蔬菜-洋葱
1.蔬菜-番茄
1.水果-葡萄
1.蔬菜-茄子
1.水果-草莓
1.水果-杏
1.果汁-菠萝
1.水稻-长粒

这是我代码,

#!

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

这里我需要打印"未找到:meat ",因为字符串'meat'在sample.txt中的任何地方都不可用。我可以使用什么RE来创建这个?或者我需要修改我的搜索逻辑吗?

83qze16e

83qze16e1#

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);
}

这样你就可以知道每根弦有几个音。

yrdbyhpb

yrdbyhpb2#

#!/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";

相关问题