开发者

How do I accomplish if-else in Perl Expect?

开发者 https://www.devze.com 2023-01-08 16:00 出处:网络
I am using Expect in Perl to accomplish one task. After sending the command I am expecting either Success or ERROR as the output, depending on which I need to print to a file saying that it was succes

I am using Expect in Perl to accomplish one task. After sending the command I am expecting either Success or ERROR as the output, depending on which I need to print to a file saying that it was successful or failed.

$exp->expect(30,
    '-re', "Success", printf LOG "Successfully Deleted \n" => sub {exp_last;},
    '-re', "ERROR",   printf LOG "Error in Deletion \n",
);

LOG is a file handle. If I use this, then even if I get Success as the output of the send command both the regular expressions are getting executed. In my log file, I am getting

开发者_开发百科
Error in Deletion
Successfully Deleted

How do I solve this?


printf is a list operator; the first printf will gobble up all the expect remaining arguments as if you'd said:

$exp->expect(30, '-re', "Success",
     printf( LOG "Successfully Deleted \n" =>
         sub {exp_last;},
         '-re',
         "ERROR",
         printf( LOG "Error in Deletion \n" )
     )
 );

So the Success case is first printing Error in Deletion, then Successfully Deleted. You should probably have instead:

$exp->expect(30,
    '-re', "Success", printf( LOG "Successfully Deleted \n" => sub {exp_last;} ),
    '-re', "ERROR",   printf( LOG "Error in Deletion \n" ),
);

except that there's no reason to use printf instead of print there.

UPDATE: As far as I can understand the Expect docs, that's not how you do multiple patterns at all, and you should be doing:

my $which_pattern = $exp->expect(30, "Success", "ERROR");
if ($which_pattern) {
    if ($which_pattern == 1) {
        print LOG "Successfully Deleted \n";
    }
    else {
        print LOG "Error in Deletion \n";
    }
}

No need for -re unless you are actually using patterns instead of explicit strings; no idea what you were trying to achieve with the sub {exp_last;} bit.

0

精彩评论

暂无评论...
验证码 换一张
取 消