2

I have an array of structs (from Class::Struct) and I am having trouble accessing their 'fields'. I've looked at other solutions such as Perl - Class::Struct Deferencing array and Perl documentation without success. My code is:

use Class::Struct;
use Data::Dump qw(dump);

struct( Tag => {
    attributes => '%',
    value => '$'
});

my @data = [];
push @data, Tag->new(attributes => { 'id' => 1 }, value => "hello world!");
dump @data;



my $tag = $data[0];
my $value = $tag->value;
print $value, "\n";

I've tried variations on blessing $tag with 'Tag' (since can't call value on unblessed ... is the current error), dereferencing $tag as a hash, and more.

1 Answer 1

6

Your error is in initialization of @data:

my @data = []; # the same as my @data = ( [] );

You declare array called @data and initialize it with one empy array ref. Next you push second element to array using push. Your class now in $data[1]. So fixed example:

struct( Tag => {
    attributes => '%',
    value => '$'
});

my @data;
push @data, Tag->new(attributes => { 'id' => 1 }, value => "hello world!");

my $tag = $data[0];
my $value = $tag->value;
print $value, "\n";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I spent a couple hours on that and never would have figured out the problem. Data dumper even showed [] in the array and I ignored it every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.