【问题标题】:Can $self be passed to a XML::Twig handler?$self 可以传递给 XML::Twig 处理程序吗?
【发布时间】:2012-07-30 22:32:29
【问题描述】:

我正在尝试解析根据类方法中给出的命令返回的不同 XML……但我想我在这里有点深。

我希望能够使用其他方法并从 XML::Twig 处理程序中访问实例的属性。

这是我在 Moose 对象中定义的一个实例方法,用于使用 XML::Twig 获取和解析 XML:

sub get_xmls {
    my $self   = shift;
    my $sehost = shift;
    my $symm   = shift;

    $self->log->info("Getting XMLs for $sehost - $symm");

    my %SYMMAPI_CALLS = (
            "Config"   => {
                'command'    => "symcfg list -sid ${symm} -v",
                'handlers'   => {
                                 'SymCLI_ML/Symmetrix' => $self->can('process_symm_info')
                            },
                'dbtable'    => "inv_emc_array"
            },
            "Pools"  => {
                'command'    => "symcfg -sid ${symm} list -pool -thin",
                'handlers'   => {
                                  'DevicePool' => $self->can('process_symm_pool')
                            },
                'dbtable'    => "inv_emc_pool"
                     }
                );

    foreach my $key (sort(keys %SYMMAPI_CALLS)) {

            my $xmldir   = $self->xmlDir;
            my $table    = $SYMMAPI_CALLS{$key}{'tbl'};
            my $handlers = $SYMMAPI_CALLS{$key}{'handlers'};
            my $command  = $SYMMAPI_CALLS{$key}{'command'};
            my $xmlfile  = qq(${xmldir}/${sehost}/${key}_${symm}.xml);

            $self->log->info("\t$key");

            if(!-d qq(${xmldir}/${sehost})) {
                mkdir(qq(${xmldir}/${sehost}))
                    or $self->log->logdie("Cant make dir ${xmldir}/${sehost}: $!");
            }

            $self->_save_symxml($command, $xmlfile);

            $self->twig(new XML::Twig( twig_handlers => $handlers ));

            $self->log->info("Parsing $xmlfile...");

            $self->twig->parsefile($xmlfile);

            $self->log->info("\t\t...finished.");
            die "Only running the first config case for now...";
    }
}

以及其中一个处理程序的定义(在我弄清楚如何正确执行此操作时,现在并没有真正做任何事情:

sub process_symm_info {
    my ($twig, $symminfo) = @_;

    print Dumper($symminfo);

}

这很好用,但我希望process_symm_info 方法能够访问 $self 以及 $self 带来的所有方法和属性。那可能吗?我做这一切都错了吗?由于我可以指定 XML 的特定部分,因此能够在处理程序中使用该数据执行其他操作会很好。

这是我第一次尝试 Perl Moose(如果你还不知道的话)。

【问题讨论】:

    标签: perl moose xml-twig


    【解决方案1】:

    目前,你有

    handlers => {
        DevicePool => $self->can('process_symm_pool'),
    },
    

    改成

    handlers => {
        DevicePool => sub { $self->process_symm_pool(@_) },
    },
    

    变量$self 将被匿名子捕获。这就是以下工作的原因:

    sub make {
        my ($s) = @_;
        return sub { return $s };
    }
    
    my $x = make("Hello, ");
    my $y = make("World!\n");
    print $x->(), $y->();  # Hello, World!
    

    闭包的世界,即:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2019-04-02
      • 2020-09-25
      • 2010-11-18
      • 2012-11-05
      相关资源
      最近更新 更多