CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Perl code enhancement

 



cognizant
Novice

May 14, 2016, 8:53 PM

Post #1 of 3 (1345 views)
Perl code enhancement Can't Post

 

Code
use strict;  
use warnings;

use XML::Twig;

my @discard = qw / abc de fghi jklm sdfe kk/;
my $filter = join '|', @discard;
$filter = qr/\b(?:$filter)\b/;

my $twig = XML::Twig->new;
$twig->parse(\*DATA);

for my $line ( $twig->findnodes('//line') ) {
$line->delete if $line->text =~ $filter;
}

$twig->print;


The above code for the following data removes lines to be discarded containing elements described in an array which are present in a parent tag.

__DATA__
<data>
<line> sdfe abc adsfefsdf </line>
<line> abc sdffedcfsdf sdf </line>
<line> sdfe </line>
<line> abc </line>
<line> sd sfefsdf </line>
<line>
<line2> aabc</line2>
<line3> kasd ads fewf 2323 </line3>
adsfefsdf
</line>
<line> fhgh kk jj hjsda </line>
<line> abc </line>
</data>


Wanna see if the code can be enhanced to remove lines if the discarded items are within a child tag of a parent tag.

Parent tag---->line
Child tag------>line2 or line3


Zhris
Enthusiast

May 15, 2016, 5:00 PM

Post #2 of 3 (1320 views)
Re: [cognizant] Perl code enhancement [In reply to] Can't Post

You need to adjust the xpath query provided to findnodes, possibilities:


Code
# select line2 and line3 elements of all line elements. 
$twig->findnodes('//line/line2 | //line/line3')

# select all child elements of all line elements.
$twig->findnodes('//line/*')


How you implement this change to cover all scenarios and retain genericity is your decision. Perhaps an array of xpath queries to run against your filter, assuming the filter doesn't vary per xpath query.

Chris


(This post was edited by Zhris on May 15, 2016, 5:05 PM)


cognizant
Novice

May 15, 2016, 5:59 PM

Post #3 of 3 (1314 views)
Re: [Zhris] Perl code enhancement [In reply to] Can't Post

Zhris,

Absolutely,

Cheers and thank you.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives