+ -
当前位置:首页 → 问答吧 → 请教perl中dispatch方法的实现方法?

请教perl中dispatch方法的实现方法?

时间:2010-11-13

来源:互联网

最近在看beginning python ,看到如下代码

class Handler:
    """
    An object that handles method calls from the Parser.

    The Parser will call the start() and end() methods at the
    beginning of each block, with the proper block name as a
    parameter. The sub() method will be used in regular expression
    substitution. When called with a name such as 'emphasis', it will
    return a proper substitution function.
    """
    def callback(self, prefix, name, *args):
        method = getattr(self, prefix+name, None)
        if callable(method): return method(*args)
    def start(self, name):
        self.callback('start_', name)
    def end(self, name):
        self.callback('end_', name)
    def sub(self, name):
        def substitution(match):
            result = self.callback('sub_', name, match)
            if result is None: match.group(0)
            return result
        return substitution

该代码中实现了所有名字为start_,end_,sub_开头的函数的抽象,比如start_html,start_heading,start_paragraph和end_html,end_heading.
我自己google了一下,类似的代码出现在imtermediate perl 和modern perl中,

my %start=
(
         $html=>\&start_html,
         $heading=>\&start_head,
         ...
}

my %end=
(...)

start_html{}
start_heading{}

使用的时候使用
for $element(@element){
         $start{$element}->();
         ...
}

我不知道有没有更接近于上述python中代码的实现,希望大家能够告诉我一下,谢谢!

作者: littlelittledog   发布时间: 2010-11-13

本帖最后由 zhlong8 于 2010-11-13 20:07 编辑

如果你理解 perl 的 OO 或者看完你上面说的 imtermediate perl 这根本就不是个问题。基本上用 perl 的语法把你上面的 Handle 照抄下就行,能用而且足够像。

楼主在 beginning python 难道楼主正在 python perl 同时入门中?

作者: zhlong8   发布时间: 2010-11-13