如何在 Perl Expect 中完成 if-else?
我正在 Perl 中使用 Expect
来完成一项任务。发送命令后,我期望输出为 Success
或 ERROR
,具体取决于我需要打印到文件中,说明它是成功还是失败。
$exp->expect(30,
'-re', "Success", printf LOG "Successfully Deleted \n" => sub {exp_last;},
'-re', "ERROR", printf LOG "Error in Deletion \n",
);
LOG
是文件句柄。如果我使用它,那么即使我得到 Success
作为 send
命令的输出,两个正则表达式都会被执行。在我的日志文件中,我得到了
Error in Deletion
Successfully Deleted
如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
printf 是一个列表运算符;第一个 printf 将吞噬所有期望的剩余参数,就像您说的那样:
因此成功的情况是首先打印删除中的错误,然后成功删除。
您可能应该改为:
除了没有理由在那里使用 printf 而不是 print 。
更新:据我所理解的 Expect 文档,这根本不是您执行多个模式的方式,您应该这样做:
不需要 -re 除非您实际上使用模式而不是显式字符串;不知道您想通过
sub {exp_last;}
位实现什么目的。printf is a list operator; the first printf will gobble up all the expect remaining arguments as if you'd said:
So the Success case is first printing Error in Deletion, then Successfully Deleted.
You should probably have instead:
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:
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.