【问题标题】:loop goes to next occurence after one match一场比赛后循环进入下一次出现
【发布时间】:2013-06-13 20:02:00
【问题描述】:

我有一个用来匹配另一个表的数组。当我执行它时,它只抓取第一次出现。例如,如果 company1 在我的数组中,它将只抓取 company1 的第一个实例,然后转到下一个搜索词,比如 company2。如果company1之后有company1.0,则只会吐出company1。我希望它在同一行吐出 company1 etc.\t company1.0 等等,因为两个列表之间会有多个匹配项。

这是我的代码:

my @attendees = ('company');
foreach $fbm (@attendees) {
    open(RFILE, '<', "file.txt")
    or die "no such file posf: $!";

    while ( $line = <RFILE> )
    { 
        if ($line =~ /$fbm/i)
        {
            print $fbm."\t". $line;
            last;
        }
        if (eof(RFILE)) 
        {
            print "posf"."\n";
        }               
    }
}
print STDERR "\n\nFINISHED!!";

我的意见:

company1
company1.0
company1 also begins with 1 but different ending
company1 can i have this one too?

我的输出:company1 期望的输出:company1\tcompany1.0\tcompany1 也以 1 开头,但不同的结尾\tcompany1 我也可以有这个吗?

【问题讨论】:

  • 哦,是的...company1 应该在数组中,而不仅仅是 'company'
  • 再澄清一下,为了输入,在每个公司名称之间有一个新行。
  • 只需编辑您的问题并进行您在此处提到的更改,它会更容易阅读。
  • 数组中只有一个元素。你如何期望更多的输出?
  • 我的猜测是last 应该在eof 被触发时发生。当然,这使得while 循环非常荒谬。这是 C 的某种翻译,是由在执行此操作之前没有费心阅读 Perl 的人完成的吗?

标签: arrays perl matching


【解决方案1】:
my @attendees = ('company');
my @whatever;
open ( my $fh, '<', "file.txt")
    or die "could not open file.txt: $!";

while ( <$fh> ) {
    chomp $_;
    push @whatever, $_;
}

foreach my $attendee ( @attendees ) {
     foreach my $thing ( @whatever ) { 
        if ($thing =~ /$attendee/i) {
            print $attendee, "\t", $thing, "\n";
        }
    }
}
print STDERR "FINISHED!\n";

也许这可以满足您的要求,但我必须承认我不太确定。

【讨论】:

  • 非常感谢...这似乎对我正在尝试做的事情更明智,我会试一试!
  • 我的@whatever 是什么;代表?只是我文件的内容?
  • 是的。我不知道它可能包含什么,所以我给变量取了一个能表达我知识的名字。
  • 而不是嵌套的 foreach 循环,为什么不只是呢? push @whatever, $_ if grep {/$_/} @attendees;
  • 因为我不知道这应该做什么。
猜你喜欢
  • 2014-03-02
  • 1970-01-01
  • 2016-06-05
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 2012-03-27
  • 1970-01-01
相关资源
最近更新 更多