如何将函数附加到类函数

时间:2015-01-04 03:18:59

标签: perl

我正在编写一个具有多种功能的Web API,例如:登录,注销,摘要等。

每当我调用任何这些功能时,我都会检查是否将发布的数据转换为JSON,然后检查护照是否已过期

每次调用api对象的函数时,如何预先添加一个执行这两项操作的函数

1 个答案:

答案 0 :(得分:1)

我认为Sub::Prepend可能对您有帮助。

样品:

use Sub::Prepend 'prepend';

    sub foo ($) {
        print "Foo executed with \@_ = (@_).\n";
    }

    BEGIN {
        prepend foo => sub {
            # This is called before foo executes.
            print "Foo was called with \@_ = (@_).\n";
            push @_, 'and more';
        }
    }

    my @bar = qw/ foo bar baz /;
    foo(@bar); # The prototype is preserved!

    __END__
    Foo was called with @_ = (3).
    Foo executed with @_ = (3 and more).