如何模拟Perl的内置反引号运算符? [英] How do I mock Perl's built-in backticks operator?

查看:125
本文介绍了如何模拟Perl的内置反引号运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对使用反引号的Perl程序进行单元测试。有没有一种方法可以模拟反引号,以便它们可以执行与执行外部命令不同的操作?

I'd like to unit test a Perl program of mine that is using backticks. Is there a way to mock the backticks so that they would do something different from executing the external command?

另一个问题显示了我需要的内容,但使用的是Ruby。不幸的是,我不能选择在该项目中使用Ruby,也不想避免出现反引号。

Another question shows what I need, but in Ruby. Unfortunately, I cannot choose to use Ruby for this project, nor do I want to avoid the backticks.

推荐答案

您可以 * 模拟内置的 readpipe 函数。当遇到反引号或 qx 表达式时,Perl将调用您的模拟函数。

You can* mock the built-in readpipe function. Perl will call your mock function when it encounters a backticks or qx expression.

BEGIN {
  *CORE::GLOBAL::readpipe = \&mock_readpipe
};

sub mock_readpipe {
  wantarray ? ("foo\n") : "foo\n";
}

print readpipe("ls -R");
print `ls -R`;
print qx(ls -R);


$ perl mock-readpipe.pl
foo
foo
foo

* -如果您具有 perl版本5.8.9 或更高版本。

* - if you have perl version 5.8.9 or later.

这篇关于如何模拟Perl的内置反引号运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆