When I run this Perl script:
#!/bin/perl
use XML::Bare;
$ob = new XML::Bare(text=>'<xml><name>Bob</name></xml>');
for $i (keys %{$ob->{xml}}) {print "KEY: $i\n";}
I get no output. However, if I put $ob inside a my():
#!/bin/perl
use XML::Bare;
my($ob) = new XML::Bare(text=>'<xml><name>Bob</name></xml>');
for $i (keys %{$ob->{xml}}) {print "KEY: $i\n";}
I get this output:
KEY: _z
KEY: _i
KEY: xml
KEY: _pos
Why does my() change this behavior so drastically, especially given
that I’m at the top level where my() should have no effect at all?
First of all, you should always begin your Perl scripts with
This will force you to declare all your variables with
mywhich catches many typos and simple mistakes.In your case, it’s not actually the
mythat causes the changed behavior, but the parentheses, which put$obin list context.Looking at the source of XML::Bare, we find this in the constructor:
Notice that the second
returnline calls->parseon the new object for you, which you forgot to do in your first example, which is why that one didn’t have any data in it.So you can say
Or
and they should be equivalent.
This is a pretty strange interface choice, but I’m not familiar with
XML::Bare.Notice also that I’ve avoided indirect method syntax (
XML::Bare->newinstead ofnew XML::Bare). This helps to avoid some nasty problems.