http://www.perlmonks.org?node_id=901497


in reply to Passing parameters for XML::twig handler

In order to pass arguments to a handler you need to use a closure:

parse_xml( $xmlfile); sub parse_xml { my( $file)= @_; my $ups_able_info= []; my $twig1 = XML::Twig->new( twig_handlers => { 'ups:TABLE_INFO/ups:field' => sub { parse +_table_info( @_, $ups_able_info); } ) ->parsefile( $file); # now $ups_table_info is filled } sub parse_table_info { my( $twig, $table_info, $ups_able_info)= @_; # note the extra argu +ment my $table_column = {}; $table_column->{$table_info->field('ups:tag')} = $table_info->fie +ld('ups:ui_name'); push(@{$ups_table_info}, $table_column); }

A good introduction to closures in Perl: Achieving closure by Simon Cozens

Also, I made a few cosmetic changes to your code, mostly to make it look a bit more modern:

Also, you data structure seems a bit weird to me, but maybe it makes sense, I don't have enough detail to tell. $ups_table_info will end up looking something like [ { ui_tag => "val" }, {ui_another_tag => "val2"}, ...],, which doesn't look like the easiest to use data.

Replies are listed 'Best First'.
Re^2: Passing parameters for XML::twig handler
by Anonymous Monk on Apr 19, 2017 at 20:31 UTC
    Great illustration ! thank you !!