为什么我没有通过这个程序获得“成功”?

时间:2013-06-14 16:34:03

标签: perl cygwin

我写了以下程序,希望获得成功。但我永远无法得到它。

my $fileName = 'myfile.txt';
print $fileName,"\n";

if (open MYFILE, "<", $fileName) {
    my $Data;
    {
        local $/ = undef;
        $Data = <MYFILE>;
    }
    my @values = split('\n', $Data);
    chomp(@values);

    if($values[2] eq '9999999999')  {
        print "Success"."\n";
    }

}

myfile.txt的内容是

160002
something
9999999999
700021

4 个答案:

答案 0 :(得分:1)

如果myfile.txt包含回车符(CR,\ r),则无法按预期工作。 另一个可能的原因是换行前的空格(LF,\ n)。

答案 1 :(得分:1)

尝试按\s*[\r\n]+

进行拆分
my $fileName = 'myfile.txt';
print $fileName,"\n";

if (open MYFILE, "<", $fileName) {
    my $Data;
    {
        local $/ = undef;
        $Data = <MYFILE>;
    }
    my @values = split(/\s*[\r\n]+/, $Data);

    if($values[2] eq '9999999999')  {
        print "Success";
    }

}

答案 2 :(得分:1)

您无需将整个文件读入数组即可检查一行。打开文件,跳过你不关心的行,然后玩你关心的行。当您完成了所需操作后,请停止阅读该文件。这样,内存中只有一行:

my $fileName = 'myfile.txt';
open MYFILE, "<", $fileName or die "$filename: $!";

while( <MYFILE> ) {
    next if $. < 3;  # $. is the line number
    last if $. > 3;

    chomp;
    print "Success\n" if $_ eq '9999999999';
    }

close MYFILE;

答案 3 :(得分:0)

my $fileName = 'myfile.txt';
open MYFILE, "<", $fileName || die "$fileName: $!";

while( $rec = <MYFILE> ) {
   for ($rec) { chomp; s/\r//; s/^\s+//; s/\s+$//; } #Remove line-feed and space characters
   $cnt++;  
   if ( $rec =~ /^9+$/ ) { print "Success\n"; last; }  #if record matches "9"s only 
                                                       #print "Success" and live the loop  
}

close MYFILE;

#Or you can write: if ($cnt==3 and $rec =~ /^9{10}$/) { print "Success\n"; last; } 
#If record 3 matches ten "9"s print "Success" and live the loop.