Search code examples
xmlperlxml-twig

XML::Twig Parse Hash to twig handler sub


Hi,

I have the following XML::Twig code to print out some tag information. However instead of parsing an array to the twig handler sub I need to parse a hash instead.

my $twig = XML::Twig->new(
    pretty_print => 'indented',
    twig_handlers =>{'tag1'=>sub{Modify_tag1_data(@_,\@Array_Vals,\@Array_Types)}}); 


sub Modify_tag1_data{
    my ( $twig, $tag1,$Array_Vals,$Array_Types) = @_;
    #
    $tag1 = $_->att('f');
    if($Array_Vals[$tag1] eq 'f' && $Array_Types[$tag1] eq 'test'){
        print $tag1 . "\n";
    }
}

However the code below, now containing the hashes instead of the arrays, gives an error saying symbo %Hash_Vals requires explicit package name and the same error for the variable %Hash_Types.

my $twig = XML::Twig->new(
    pretty_print => 'indented',
    twig_handlers =>{'tag1'=>sub{Modify_tag1_data(@_,\%Hash_Vals,\%Hash_Types)}}); 


sub Modify_tag1_data{
    my ( $twig, $tag1,$Hash_Vals,$Hash_Types) = @_;
    #
    $tag1 = $_->att('f');
    if($Hash_Vals{$tag1} eq 'f' && $Hash_Types{$tag1} eq 'test'){
        print $tag1 . "\n";
    }
}

What is wrong?


Solution

  • This question seems a bit misleading. If you are getting: "%Hash_Vals requires explicit package name and the same error for the variable %Hash_Types."

    ... that means you haven't declared these variables. It's not a lot to do with XML::Twig or XML parsing at all.

    In your sub, you're doing something strange too - I suspect you're not doing what you want with:

    sub Modify_tag1_data{
        my ( $twig, $tag1,$Hash_Vals,$Hash_Types) = @_;
        #
        $tag1 = $_->att('f');
        if($Hash_Vals{$tag1} eq 'f' && $Hash_Types{$tag1} eq 'test'){
            print $tag1 . "\n";
        }
    }
    

    Because $Hash_Vals in your parameters has no connection with $Hash_Vals{$tag1} aside from looking similar. You probably want $Hash_Vals -> {$tag1} but it's hard to tell without knowing what %Hash_Vals actually contains.