Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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

by AppleFritter (Vicar)
on Apr 02, 2017 at 21:38 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1186753]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2024-04-19 15:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found