开发者

How best to override/wrap core functions like sysread when they are called in another package

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 :)


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;
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜