gpt4 book ai didi

perl - 如何模拟内置运算符

转载 作者:行者123 更新时间:2023-12-05 00:51:04 25 4
gpt4 key购买 nike

我需要模拟像 unlink 这样的内置操作符和 rename作为测试套件的一部分。我无法使用 Test::MockObject 使其工作

>> my $mock = Test::MockObject->new();
>> $mock->mock('unlink', sub { print "Mocked!\n"; });
>> unlink "foo";
0

是否可以模拟这样的内置函数?

最佳答案

overriding core functions :

To override a Perl built-in routine with your own version, you need to import it at compile-time. This can be conveniently achieved with the subs pragma. This will affect only the package in which you've imported the said subroutine:

   use subs 'chdir';
sub chdir { ... }
chdir $somewhere;

To override a built-in globally (that is, in all namespaces), you need to import your function into the CORE::GLOBAL pseudo-namespace at compile time:

    BEGIN {
*CORE::GLOBAL::hex = sub {
# ... your code here
};
}

The new routine will be called whenever a built-in function is called without a qualifying package:

   print hex("0x50"),"\n";            # prints 1

In both cases, if you want access to the original, unaltered routine, use the CORE:: prefix:

   print CORE::hex("0x50"),"\n";      # prints 80


另见 the relevant section in perldoc perlsub :

When you override a built-in, your replacement should be consistent (if possible) with the built-in native syntax. You can achieve this by using a suitable prototype. To get the prototype of an overridable built-in, use the prototype function with an argument of "CORE::builtin_name" (see prototype).

Note however that some built-ins can't have their syntax expressed by a prototype (such as system or chomp). If you override them you won't be able to fully mimic their original syntax.

The built-ins do, require and glob can also be overridden, but due to special magic, their original syntax is preserved, and you don't have to define a prototype for their replacements. (You can't override the do BLOCK syntax, though).

require has special additional dark magic: if you invoke your require replacement as require Foo::Bar, it will actually receive the argument "Foo/Bar.pm" in @_. See require.

And, as you'll have noticed from the previous example, if you override glob, the <*> glob operator is overridden as well.

In a similar fashion, overriding the readline function also overrides the equivalent I/O operator <FILEHANDLE>. Also, overriding readpipe also overrides the operators `` and qx//.

Finally, some built-ins (e.g. exists or grep) can't be overridden.

关于perl - 如何模拟内置运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44807612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com