如何在Perl中读取文件,直到它匹配某些字符串/值

时间:2015-05-25 12:00:48

标签: perl

我有一个文本文件,其中包含

等条目
123
123
234
456
789
654
123
123
123

我正在尝试编写一个打开并读取文件的perl脚本(这样做时,它必须忽略第二个123并通读直到下一个123重复):

期望的输出:

123 # Keep
123 # Ignore
234 # Keep
456 # Keep
789 # Keep
654 # Keep
123 # Keep and stop here

1 个答案:

答案 0 :(得分:1)

#!/usr/bin perl
use strict;
use warnings;

# open my $file, '<', 'in.txt' or die $!; # If you're reading in from a file use this

my %seen;
while (<DATA>) {
    chomp;
    $seen{$_}++;    
    next if $seen{$_} == 2;
    print "$_\n";
    last if $seen{$_} > 2;
}


__DATA__
123
123
234
456
789
654
123
123
123

--- ---输出

123
234
456
789
654
123