等于if语句不按预期工作

时间:2012-06-28 23:18:09

标签: perl

use Text::Diff;
my $count;
our $stats2 = 0;
for($count = 0; $count <= 1000; $count++){
    my $data_dir="archive/oswiostat/oracleapps.*dat";
    my $data_file= `ls -t $data_dir | head -1`;
    chomp($data_file);
    while(defined($data_file)){
        print $data_file;
        open (DAT,$data_file) || die("Could not open file! $!");
        my @stats1 = stat $data_file;
        my @raw_data=<DAT>;
        close(DAT);
        print "Stats1 is :$stats1[9]\n";
        sleep(5);
        print "Checking $stats1[9] equals $stats2\n";
        if(chomp($stats1[9]) != chomp($stats2)){
            print "I am here";
            my @diff = diff \@raw_data, $data_file, { STYLE => "Context" };
            print @diff || die ("Didn't see any updates $!");
        }
        $stats2 = $stats1[9];
        print "Stat2: $stats2\n";
    }
}

输出

[oracle@oracleapps osw]$ perl client_socket1.pl
archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1900.datStats1 is :1340925244
Checking 1340925244 equals 0
Stat2: 1340925244
archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1900.datStats1 is :1340925298
Checking 1340925298 equals 1340925244
Stat2: 1340925298
archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1900.datStats1 is :1340925304
Checking 1340925304 equals 1340925298
Stat2: 1340925304
archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1900.datStats1 is :1340925304
Checking 1340925304 equals 1340925304
Stat2: 1340925304
archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1900.datStats1 is :1340925304

当输出显示@ stats1 [9]不等于$ stats2时,它应该进入if循环并打印“我在这里”,但它不是那样工作的。你能否找出问题所在。

2 个答案:

答案 0 :(得分:0)

这是你的问题:

if (chomp($stats1[9]) != chomp($stats2)) { 

应该是

chomp($stats1[9]);
chomp($stats2);
if ($stats1[9] != $stats2) { 

以及

my @diff = diff \@raw_data, $data_file, { STYLE => "Context" }; 
print @diff || die ("Didn't see any updates $!"); 

应该是

my $diff = diff \@raw_data, $data_file, { STYLE => "Context" }; 
print $diff || die ("Didn't see any updates $!"); 

答案 1 :(得分:0)

chomp()将字符串修改为副作用,并返回从字符串中删除的换行符,而不是修改后的字符串。你可能想写

chomp $stats1[9];
chomp $stats2;
if($stats1[9] != $stats2) {