Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Seekers of Perl Wisdom

( #479=superdoc: print w/ replies, xml ) Need Help??

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
NewBie Need Tuto Guide
4 direct replies — Read more / Contribute
by Abdelbari619
on Jun 03, 2015 at 14:08

    Hi Monks I'm New Here and in Perl Coding :) Can You Give Good Tuto For starting Coding Perl :)

Stings mangled on printing
1 direct reply — Read more / Contribute
by gordu
on Jun 03, 2015 at 13:37

    Over the years I've dabbled in perl and every once in a while I get bit by this problem. Basically strings I try and print come out mangled. As an example

    #!/usr/bin/perl use strict; use Device::SerialPort; use FileHandle; my $fh = FileHandle->new; my $port = Device::SerialPort->new("/dev/ttyACM1"); $port->databits(8); $port->baudrate(57600); # <-- match to arduino settings $port->parity("none"); $port->stopbits(1); $port->dtr_active(0); my $i=1000; my $rt = 0; my $rh = 0; my $it = 0; my $foos=""; select(STDOUT); while($i> 0) { my $inp = $port->lookfor; if($inp ne "") { if($inp =~ /Remote Temp:/) { $rt = $inp; $rt =~ s/Remote Temp://; print "inp=$inp\n"; print "rt=$rt\n"; $foos="$rt does not print rt \n"; print $foos; print "rt=$rt\n\n"; } } } $port->close; undef $port;
    The output from running this is
    inp=Remote Temp:22.30 rt=22.30 does not print rt rt=22.30

    Whats happening? BTW the input is a string like "Remote Temp:22.30"

Graphics math.
2 direct replies — Read more / Contribute
by BrowserUk
on Jun 03, 2015 at 12:30

    These questions are mostly intellectual curiosity rather than an immediate requirement; and possibly off topic, though the code below is taken from one of my programs that is under active development.

    I have a clip region defined in terms of several partially overlapping ellipses.

    I tried to draw a picture, but it defeated my ascii art skills, but think the interior space of the Olympic Rings and wanting to only show (or exclude) those pixels that fall within (or outside) the combined perimeter.

    And for generality -- and because the formula isn't much more complex -- define the rings as ellipses rather than circles. So the individual components of the region are stored as:

    my @clips = ( { cx => $X * 0.500, cy => $Y * 0.4, rx2 => ( $X * 0.295 )**2, ry +2 => ( $Y * 0.40 )**2 }, { cx => $X * 0.500, cy => $Y * 0.6, rx2 => ( $X * 0.390 )**2, ry +2 => ( $Y * 0.34 )**2 }, { cx => $X * 0.428, cy => $Y * 0.748, rx2 => ( $X * 0.067 )**2, ry +2 => ( $Y * 0.038)**2 }, ... };

    So I have code that does something like:

    sub clip { my( $x, $y ) = @_; return 1 if ( $x - $clips[0]{cx} )**2 / $clips[0]{rx2} + ( $y - $c +lips[0]{cy} )**2 / $clips[0]{ry2} < 1; return 1 if ( $x - $clips[1]{cx} )**2 / $clips[1]{rx2} + ( $y - $c +lips[1]{cy} )**2 / $clips[1]{ry2} < 1; return 1 if ( $x - $clips[2]{cx} )**2 / $clips[2]{rx2} + ( $y - $c +lips[2]{cy} )**2 / $clips[2]{ry2} < 1; ... return 0; }

    If the point is within any of the rings, return true (draw it), otherwise return false (don't).

    Without resorting to rasterising the whole thing, which requires more tests; more space and doesn't work with scaling, is there any (simple) way to combine the formulae of the ellipses that would result in less tests?


    On a related, but probably fanciful note, imagine I was only interested in seeing the region of the interior that lies within half a minor axis of the perimeter of the combined region, can that be defined parametrically?

    And finally, if I wanted to split the entire perimeter at one point, stretch it out to a straight horizontal line, and display the half minor axis region, above that line, what on earth would the transform look like?

    (Some distortion would be involved -- similar to the poles under Mercator Projection -- but that is okay.)


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Is this a severe error?
6 direct replies — Read more / Contribute
by Anonymous Monk
on Jun 03, 2015 at 10:39
    Hi Monks, I get this error in my code:
    Use of uninitialized value in concatenation (.) or string in line 1245

    The snippet of code is the following:
    for (my $s=$start_of_barrel_region; $s<=(($start_of_barrel_region+$len +gth_of_barrel_region)); $s++) { my $aa_pos=$s+1; print PLP_FILE "$aa_pos\t".$split_query_for_PLP[$s]."\t".$hash_p +lp_lbl_barrel_region_only{$s}."\n"; }

    The erroneous line seems to be :
    my $aa_pos=$s+1;
    The program executes without problem, I am just wondering why I get this error and how I can fix it...
    Thank you in advance
Using XPaths with XML::LibXML and XPathContext
2 direct replies — Read more / Contribute
by worik
on Jun 02, 2015 at 19:24

    I am trying to parse some simple XML in XML::LibXML and I have struck a problem. The domain is WebDAV.

    A PROPFIND request from a user can send some very simple XML, but in a variety of semantically identical but syntactically different forms.

    For a simple example:

    <?xml version="1.0" encoding="utf-8" ?> <propfind xmlns="DAV:"> <propname/> </propfind>
    <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:propname/> </D:propfind>

    TO get the 'propfind' node valid XPaths are

    //propname
    //DAV:propname
    /propfind/propname
    /DAV:propfind/DAV:propname

    surely? But none of them work with XPathContext except in one special case (below) where there is no need for it anyway.

    Below are my test code and the results. In it I register 'D' as a prefix for 'DAV:' and so using a XPath with 'D' as prefix works where the XML uses it too. But that is not good enough for where the XML uses 'DAV:' as a default namespace 'D' as a prefix should work too. Surely?

    #!/usr/bin/perl -w use strict; use XML::LibXML; sub testfn { my $content = shift or die; my $xpath = shift or die; $|++; my $parser = XML::LibXML->new(); my $dom = $parser->parse_string($content); my @propfind = (); @propfind = $dom->findnodes($xpath); print ref($dom)."::findnodes('$xpath') (NOT XPathContext) ". scalar(@propfind)." nodes\n"; my $xc = XML::LibXML::XPathContext->new($dom); $xc->registerNs('D', 'DAV:'); @propfind = $xc->findnodes($xpath); print ref($xc)."::findnodes('$xpath') ".scalar(@propfind)." nodes\ +n"; } # Example from RFC4918 my $txt1 = '<?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:propname/> </D:propfind> '; my $txt2 = '<?xml version="1.0" encoding="utf-8" ?> <propfind xmlns="DAV:"> <propname/> </propfind> '; my $xpath1 = '/DAV:propfind/DAV:propname'; my $xpath2 = '/propfind/propname'; my $xpath3 = '/D:propfind/D:propname'; print "\$txt1\n".$txt1."\n"; print "\$txt1 \$xpath1 \n"; eval { &testfn($txt1, $xpath1); }; if($@){ print "Failed \$xpath $xpath1\n"; } print "\$txt1 \$xpath2 \n"; eval{ &testfn($txt1, $xpath2); }; if($@){ print "Failed \$xpath $xpath2\n"; } print "\$txt1 \$xpath3 \n"; eval{ &testfn($txt1, $xpath3); }; if($@){ print "Failed \$xpath $xpath3\n"; } print "\$txt2\n".$txt2."\n"; print "\$txt2 \$xpath1 \n"; eval{ &testfn($txt2, $xpath1); }; if($@){ print "Failed \$xpath $xpath1\n"; } print "\$txt2 \$xpath2 \n"; eval { &testfn($txt2, $xpath2); }; if($@){ print "Failed \$xpath $xpath2\n"; } print "\$txt2 \$xpath3 \n"; eval { &testfn($txt2, $xpath3); }; if($@){ print "Failed \$xpath $xpath3\n"; }

    The results:

    $txt1 <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:propname/> </D:propfind> $txt1 $xpath1 Failed $xpath /DAV:propfind/DAV:propname $txt1 $xpath2 XML::LibXML::Document::findnodes('/propfind/propname') (NOT XPathConte +xt) 0 nodes XML::LibXML::XPathContext::findnodes('/propfind/propname') 0 nodes $txt1 $xpath3 XML::LibXML::Document::findnodes('/D:propfind/D:propname') (NOT XPathC +ontext) 1 nodes XML::LibXML::XPathContext::findnodes('/D:propfind/D:propname') 1 nodes $txt2 <?xml version="1.0" encoding="utf-8" ?> <propfind xmlns="DAV:"> <propname/> </propfind> $txt2 $xpath1 Failed $xpath /DAV:propfind/DAV:propname $txt2 $xpath2 XML::LibXML::Document::findnodes('/propfind/propname') (NOT XPathConte +xt) 0 nodes XML::LibXML::XPathContext::findnodes('/propfind/propname') 0 nodes $txt2 $xpath3 Failed $xpath /D:propfind/D:propname
Perl file rename
4 direct replies — Read more / Contribute
by keltan
on Jun 02, 2015 at 19:22

    HI

    I've got problem i need to write file renamer. I know that there are topics on this forum with answers but i need to write slightly different code and i hope you will help. Yes this is my homework but i dont need direct answers i appreciate tips.
    !/usr/bin/perl -w use strict; my $dirname; $dirname = 'D:\test'; my $test = $ARGV[0]; my $test1 = $ARGV[1]; my $pattern = qr/$test/; my $pattern1 = qr/$test1/; opendir(DIR, $dirname) or die "Can't opendir $dirname: $!"; while ( defined (my $file = readdir DIR) ) { next if $file =~ /^\.\.?$/; my $new = $file; $new =~ s/$pattern/$pattern1/; rename($file,$new) }
    What i need to write is a script which after this command: ./rename *.pl "s/^/old_/" will add to all files with extension .pl prefix old_ I've been trying few approaches but all failed. Funny thing is that in other languages i don't have that problem only PERL always beat me down.
scp output without having to use "Net::SCP" in Perl
4 direct replies — Read more / Contribute
by pjzero@90
on Jun 02, 2015 at 17:13
    Question, I'm trying to scp output/file from one machine to another without using Net::SCP, any ideas? Example:
    #system("/usr/bin/tmp",$output,"$USER\@$host:/tmp/LOGS/");
    While trying to do this in a for loop:
    my @OUTPUT = `ls -ltr /tmp` foreach my $output (@OUTPUT) { chomp ($output); system("scp $output user@server:/tmp/LOGS"); } scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2 scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2 scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2 scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2 scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2 scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2 scp: illegal option -- w usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file +] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 [...] [[user@]host2:]file2
    No luck.....
Match two files using regex
5 direct replies — Read more / Contribute
by chemshifts
on Jun 02, 2015 at 13:34

    Hello, This question was posted and answered on StackOverflow: I have two files that I would like to match based on the first letter of the second column in File1 and the first letter of the third column in File2. For example:

    File1 1 H 35 1 C 22 2 H 20 2 C 30 File 2 A 1 HB2 MET 1 A 2 CA MET 1 A 3 HA ASP 2 A 4 CA ASP 2 Output 1 MET HB2 35 1 MET CA 22 2 ASP HA 20 2 ASP CA 30
    Below is my script:
    #!/usr/bin/perl use strict; use warnings; my %data; open (SHIFTS,"file1.txt") or die; open (PDB, "file2.txt") or die; while (my $line = <PDB>) { chomp $line; my @fields = split(/\t/,$line); $data{$fields[4]} = $fields[2]; } close PDB; while (my $line = <SHIFTS>) { chomp($line); my @columns = split(/\t/,$line); my $value = ($columns[1] =~ m/^.*?([A-Za-z])/ ); } if (my $value = $data{"$_"}) print "$columns[0]\t$fields[3]\t$value\t$data{$value}\n"; close SHIFTS; exit;

    I am not sure how to implement the match, my if statement above is not correct. Any advice would be greatly appreciated.

XML Parse
4 direct replies — Read more / Contribute
by tfeitor
on Jun 02, 2015 at 13:07
    Hi everyone, I'm new with Perl and tried to parse the following xml file. I try thing's like libXML and other thing's, but I couldn't get values like code_a / name. Can someone Help me with this. Thanks in Advance Tiago
    <?xml version="1.0"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envel +ope/"> <soapenv:Body> <dlwmin:getBookById xmlns:dlwmin="http://www.test.com/integration" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <result xmlns="http://www.test.com/integration/integration"> <status> <state>0</state> </status> <books> <num>12345</num> <book> <code_a>11111</code_a> <name>Come to the Dark Side 1st Ed</name> <otherVal>ABC</otherVal> <otherVal2>1999</otherVal2> </book> <book> <code_a>22222</code_a> <name>Come to the Dark Side 2nd Ed</name> <otherVal>ABC</otherVal> <otherVal2>2001</otherVal2> </book> <Title>Come to the Dark Side</Title> <typeOfBook>SciFi</typeOfBook> <writer>Darth Vader</writer> </books> </result> </dlwmin:getBookById> </soapenv:Body> </soapenv:Envelope>
    Like I said before I'm new with perl :) 4 hours, I need to parse a lot of files in a Production Env, I tried the code bellow:
    use strict; use warnings; use XML::LibXML; use XML::LibXML qw( ); my $parser = XML::LibXML->new(); my $doc = $parser->parse_file('out.xml'); for my $result ($doc->findnodes('/books/book')) { for my $interv ($result->findnodes('book')) { my $bk = $interv->find('code_a'); my $bk_name = $interv->find('name'); print("$bk - $bk_name"); } }
    and this one (I couldn't understand how to interate with the hash):
    use strict; use XML::Simple; use Data::Dumper; my $doc = XMLin('out.xml'); print Dumper($doc);
    antoher thing the xml was in one line. thanks
Parse for a list in a long string
4 direct replies — Read more / Contribute
by vitoco
on Jun 02, 2015 at 13:00

    I want to get a list of items from a long text string with a given format. The format is pretty simple, but the number of items in the list is variable, also it is the number of lists in the same string. Of course, there are many other things in the string that must be discarded.

    I tried a single regular expression to capture the items to an array, but I can get only the first or the last element or each identified list...

    This is a test code:

    #!perl use strict; use warnings; while (<DATA>) { chomp; s!\s+! !g; my $txt = $_; print "$_\n"; my @items = (); print "FOUND: @items\n" if (@items = ($txt =~ m!\btest \w+(?:(?: is) +? \w+)?(?: ?, ?(\w+)(?:(?: is)? \w+)?)+!ig)); } __DATA__ this line has nothing, nothing, nothing... 1 , 2, 3, 4 is four, 5, 6 test 00,11 is one,22, 33 is three,44,55 is + the best, and this is not a test 111, 222, 333 as random words to + finish this should be a test, but nothing must be returned 4444, 7777, 9999 i +s garbage

    In this example, the lists starts with the string "test", the elements are delimited by a comma, each element could be followed by an optional "is" and another word (must be discarded), and the first element of the list is not important and must be ignored. The given data has 3 lines, and only the 2nd one has two lists, the 1st and 3rd have none. The expected result is:

    FOUND: 11 22 33 44 55 222 333

    What I got is:

    FOUND: 55 333

    If I remove the last plus sign, I get:

    FOUND: 11 222

    If I remove the "g" modifier, I get only one list (with one item):

    FOUND: 55

    What am I missing?

    Thanks!!!


Add your question
Title:
Your question:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":


  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others pondering the Monastery: (11)
    As of 2015-06-03 19:58 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      What kind of chocolate gives you the most pleasure?















      Results (138 votes), past polls