http://qs321.pair.com?node_id=1186753


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'