Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Assigning variables and persistence using Lib::LibXML::Reader

by AppleFritter (Vicar)
on Apr 02, 2017 at 21:38 UTC ( #1186753=note: print w/replies, xml ) Need Help??


in reply to Assigning variables and persistence using Lib::LibXML::Reader

By "persist", do you mean that the data read from the file will be available after the while loop's done? If so, declare your variable(s) before the loop, outside the loop's body.

EDIT: OK, scratch that, I misunderstood your question. (It's a Sunday night, that's my excuse and I'm sticking to it.) Looking at your sample XML snippet (not well-formed, BTW), it seems that $reader->localName equals "price" twice, when the price tag gets opened and when it gets closed. So $price gets set correctly, but then overwritten again.

The easiest (quickest, dirtiest) way to deal with that is to use ||= or //=:

while($reader->read) { $price //= $reader->readInnerXml if $reader->localName eq 'price'; } print $price;

This will only assign to $price if $price is false (||=) or undefined (//=), and leave it be otherwise.

Replies are listed 'Best First'.
Re^2: Assigning variables and persistence using Lib::LibXML::Reader
by shmem (Chancellor) on Apr 02, 2017 at 21:54 UTC
    If so, declare your variable(s) before the loop, outside the loop's body.

    If he doesn' use strict, the undeclared variable $price is a package global and will persist after the loop, carrying the value of the last assignment:

    # look ma, no strict for (1..4) { $price = $_; } print $price,$/ __END__ 4
    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2020-05-30 12:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (171 votes). Check out past polls.

    Notices?