Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Code efficiency ?

by converter (Priest)
on May 01, 2003 at 15:26 UTC ( #254678=note: print w/ replies, xml ) Need Help??


in reply to Efficiently inserting XML data

As others have already mentioned, simple regular expressions aren't the best tool for extracting data from SGML documents, but there are other parts of your code that are interesting and could be improved.

After I wrote this I refreshed the page and noticed that a few others had already done the same, but I think there are a few changes and comments here that aren't covered in the other posts. Sorry if I'm redundant.

This code compiles but has not been tested.

#!/usr/bin/perl use warnings; use strict; # if the argument to die ends with newline, die # won't print the line number: # open (READ, "test.xml") || die "ERROR: $!\n"; # you probably want to know which file the error # relates to and the mode (read or write): open READ, "< test.xml" or die "ERROR opening test.xml for reading: $! +"; # NOTE that we use 'or', a lower-precedence logical # operator so that we can leave off the parentheses # around the arguments to open() my @array = <READ>; # close can fail. if it does, you probably want to know # about it: close READ or die "ERROR closing READ filehandle: $!"; # see above comments # open (WRITE, ">new.xml") || die "ERROR: $!\n"; open WRITE, "> new.xml" or die "ERROR creating new.xml: $!"; # make WRITE the default filehandle select WRITE; foreach (@array) { # '<' and '!' are not meta-characters so there's no # need to escape them: if (/<!-- Testing XML -->/) { # use a here-document (see the perlop man page) print <<_EOF_; <bar> <name> TEST </name> <type> Foo </type> <!-- PDP Status --> <unknown_sec> 0 </unknown_sec> </bar> _EOF_ } # in /PATTERN/, the '/' character is your delimiter. # if the pattern delimiter occurs in the pattern, # instead of escaping the delimiter, use a different # delimiter with the explicit m operator. here we # use '!' as our delimiter: if (m!</ Test Tag>!) { print "<bar><value> TEST </value></bar>\n"; } # \n$ : this is redundant. the $ anchor matches an optional newlin +e if (m!</v></row>$!) { # note the use of '@' instead of '/' as the delimiter: s@</row>$@@; $_ .= "<v> UnKnown </v></row>\n"; print; # prints $_ by default } else { print; } } close WRITE or die "ERROR closing WRITE filehandle: $!";


Comment on Re: Code efficiency ?
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://254678]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2014-11-27 17:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (186 votes), past polls