Why isn't my object attribute populated?

Viewed 125

Given this oversimplified XML file:

<Foo>Bar</Foo>

And this code which extracts the value for the Foo element:

use XML::Rabbit;
use Data::Dump::Tree;

class RunInfo does XML::Rabbit::Node {
    has $.foo is xpath("/Foo");
}

sub MAIN ( $file! ) {

    my $xml = RunInfo.new( file => $file );

    dump $xml;

    put "-----------------------";
    put "Foo is $xml.foo()";
}

You'll see that the value for foo is Nil, even though the output shows Foo is Bar:

.RunInfo @0
├ $.foo = Nil
├ $.context is rw = .XML::Document @1
│ ├ $.version = 1.0.Str
│ ├ $.encoding = Nil
│ ├ %.doctype = {0} @2
│ ├ $.root = .XML::Element @3
│ │ ├ $.name is rw = Foo.Str
│ │ ├ @.nodes is rw = [1] @4
│ │ │ └ 0 = .XML::Text @5
│ │ │   ├ $.text = Bar.Str
│ │ │   └ $.parent is rw = .XML::Element §3
│ │ ├ %.attribs is rw = {0} @7
│ │ ├ $.idattr is rw = id.Str
│ │ └ $.parent is rw = .XML::Document §1
│ ├ $.filename = example.xml.Str
│ └ $.parent is rw = Nil
└ $.xpath is rw = .XML::XPath @9
  ├ $.document = .XML::Document §1
  └ %.registered-namespaces is rw = {0} @11
-----------------------
Foo is Bar

(Disclaimer: I came across this behavior today in my code, so I wrote it up Q & A style. Other answers welcome.).

By the way, here are links to XML::Rabbit and Data::Dump::Tree.

2 Answers
Related