我的问题是:如何将一些参数传递给
XML:Twig的处理程序,以及如何从处理程序返回结果.
@H_404_20@解决方法
这是我的代码,硬编码:
< counter name =“music”,report type =“month”,stringSet index = 4>.
如何通过使用参数$counter_name,$type,$id来实现这一点?以及如何返回string_list的结果?谢谢(抱歉,我没有在这里发布xml文件,因为我遇到了一些麻烦.<和>中的任何内容都被忽略了).
use XML::Twig; sub parse_a_counter { my ($twig,$counter) = @_; my @report = $counter->children('report[@type="month"]'); for my $report (@report){ my @stringSet = $report->children('stringSet[@index=”4”]'); for my $stringSet (@stringSet){ my @string_list = $stringSet->children_text('string'); print @string_list; # in fact I want to return this string_list,# not just print it. } } $counter->flush; # free the memory of $counter } my $roots = { 'counter[@name="music"]' => 1 }; my $handlers = { counter => \&parse_a_counter }; my $twig = new XML::Twig(TwigRoots => $roots,TwigHandlers => $handlers); $twig->parsefile('counter_test.xml');
将参数传递给处理程序的最简单,通常的方法是使用闭包.这是一个很大的词,但是一个简单的概念:你称这个处理程序就像这个tag => sub {handler(@_,$my_arg)}和$my_arg将传递给处理程序.
Achieving Closure对该概念有更详细的解释.
以下是我编写代码的方法.我使用Getopt :: Long进行参数处理,并使用qq {}代替包含XPath表达式的字符串的引号,以便能够在表达式中使用引号.
#!/usr/bin/perl use strict; use warnings; use XML::Twig; use Getopt::Long; # set defaults my $counter_name= 'music'; my $type= 'month'; my $id= 4; GetOptions ( "name=s" => \$counter_name,"type=s" => \$type,"id=i" => \$id,) or die; my @results; my $twig= XML::Twig->new( twig_roots => { qq{counter[\@name="$counter_name"]} => sub { parse_a_counter( @_,$id,\@results); } } ) ->parsefile('counter_test.xml'); print join( "\n",@results),"\n"; sub parse_a_counter { my ($twig,$counter,$results) = @_; my @report = $counter->children( qq{report[\@type="$type"]}); for my $report (@report){ my @stringSet = $report->children( qq{stringSet[\@index="$id"]}); for my $stringSet (@stringSet){ my @string_list = $stringSet->children_text('string'); push @$results,@string_list; } } $counter->purge; # free the memory of $counter }