'/shipment/box' => sub { _move(@_); 1; } #### # '/shipment/box' => sub { _move(@_); 1; } #wrong # to '/shipment/box' => \&_move, #### sub _move { unless ($_[1]->descendants('slip')){ $_[0]->purge(); return; } foreach my $descendant ... #### #!/usr/bin/perl # use 5.020; unneeded aside from the say use strict; use warnings; use XML::Twig; ## ## This works as expected ## my $working_xml = XML::Twig->new( twig_handlers => { #'/shipment/box' => sub { _move(@_); 1; }, #why? and why 1; at the end? '/shipment/box' => \&_move, }, pretty_print => 'indented', )->safe_parse( <<"XML" potato pear peach apple XML ); print "\n\n---------------------\n\n"; ## ## This ALSO WORKS FINE NOW!! ## my $broken_xml = XML::Twig->new( twig_handlers => { '/shipment/box' => \&_move, }, pretty_print => 'indented', )->safe_parse( <<"XML" potato pear peach nothing here! XML ); # ---------- sub _move { unless ($_[1]->descendants('slip')){ $_[0]->purge(); return; } foreach my $descendant ( $_[1]->descendants('slip') ) { $descendant->set_att('_TYPE' => 'produce'); $descendant->move('before', $_[1]); } $_[1]->delete; $_[0]->flush(); #1; # why? } ## OUTPUT potato pear peach apple --------------------- potato pear peach