当在另一个包中调用 sysread 等核心函数时,如何最好地覆盖/包装它们

发布于 2024-11-08 02:29:32 字数 660 浏览 2 评论 0 原文

我正在开发一个用 Perl 编写的相当复杂的应用程序。我对这门语言相当有经验,但我只是被难住了。

我正在使用一个模块 Foo,它使用 sysread 和 syswrite 对我传递给其构造函数的文件句柄(在本例中为双向套接字)进行各种操作。

我想要执行以下操作:从我正在编写的另一个模块(我们称之为 Bar),我想更改 sysread/write 的行为方式 仅当从属于 Foo 的方法内调用时

Sysread等人需要在其他地方正常工作。可以放心地假设 Foo 中 sysread 的使用不会改变。

我想要这样做的原因是我需要跟踪从上述文件句柄读取/写入的字节数。此时,这似乎是我获取此信息的唯一方法 - 基本上保存系统读/写的返回值。

我使用 CPAN 的任何东西都没有问题,只要它质量好。


更新:我找到了针对我的具体问题的更好解决方案,并在此处发布了代码:

https:// github.com/Hercynium/Tie-Handle-CountChars

它似乎在我的应用程序中运行得很好,但在我更彻底地测试它并编写一些实际的代码之前,我不会将其发布到 CPAN单元测试:)

I'm working on a fairly complex application written in Perl. I'm fairly experienced with the language, but I'm just stumped on this.

I'm using a module, Foo, which uses sysread and syswrite for various operations on a file-handle (a bi-directional socket, in this case) that I pass to its constructor.

I want to do the following: From another module I am writing, (let's call it Bar), I want to change the way that sysread/write behave only when called from within methods that belong to Foo

Sysread et al need to work as normal everywhere else. It can be safely assumed that the use of sysread will not change in Foo.

The reason I want to do this is that I need to track the number of bytes being read from/written to the afore-mentioned file handle. At this point, this seems like the only way I can get this information - basically saving the return value from sysread/write.

I have no problems using anything from the CPAN, as long as it's of good quality.


Update: I found a better solution to my specific problem, and have posted the code here:

https://github.com/Hercynium/Tie-Handle-CountChars

It seems to be working very well in my application, but I won't be posting it to the CPAN until I've more thoroughly tested it, plus written some actual unit tests :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如日中天 2024-11-15 02:29:32

您可以通过创建自己的 Foo::sysread 函数来完成此操作,该函数通过记录返回值来包装核心函数。可以使用 类::方法::修饰符:

package Foo;

use strict;
use warnings;

# ... other code...

use Class::Method::Modifiers;
around sysread => sub {
    my $orig = shift;

    my $return = CORE::sysread(@_);

    # do something with $return

    return $return;
};

You could do this by creating your own Foo::sysread function, which wraps the core function by logging the return value. The wrapping can be done automatically (preventing you from having to mess about with the symbol table yourself) with Class::Method::Modifiers:

package Foo;

use strict;
use warnings;

# ... other code...

use Class::Method::Modifiers;
around sysread => sub {
    my $orig = shift;

    my $return = CORE::sysread(@_);

    # do something with $return

    return $return;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文