Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 676
  • Last Modified:

Class::Struct array of structs possible? (Perl)

Experts,

I'm using the Perl Class::Struct module and would like to find out if it's possible to create a struct that has an array member which should then contain other arrays or hash arrays.

Is that possible and how would I push and pull arrays to the array member?

This is what I had in mind:

my %body_element = ();
$body_element{'first'} = 1;
$body_element{'second'} = 2;

push @{ $my_message->message_body }, %body_element ;

struct Message => {
    message_header => '@',
    message_body => '@',
};
0
php-newbie
Asked:
php-newbie
  • 2
  • 2
1 Solution
 
Justin MathewsCommented:
Yes, that should work:
use Class::Struct;
 
struct Message => {
    message_header => '@',
    message_body => '@',
};

my $my_message = Message->new();

my %body_element = ();
$body_element{'first'} = 1;
$body_element{'second'} = 2;

push @{ $my_message->message_body }, %body_element ;

print "$_\n" for (@{$my_message->message_body});

Open in new window

0
 
php-newbieAuthor Commented:
Unfortunately using your solution when I dump the struct I see that the hash array is stored as elements of the regular array 'body_element':

'Message::body_element' => [
                                   'first',
                                   1,
                                   'second',
                                   '2'
                                 ]

0
 
php-newbieAuthor Commented:
One possible workaround I found was to define a second struct that can be stored in the array within the first struct. That seems to work.

For example:
push @{ $my_message->body_content }, Carrier_Info->new(name => "Paul Lalli", abbrev =>
"PL");
my $carrier_info = pop(@{$my_message->body_content});
0
 
Justin MathewsCommented:
Sorry, you should be adding a reference to the hash (\%body_element) as below:


use Class::Struct;
 
struct Message => {
    message_header => '@',
    message_body => '@',
};

my $my_message = Message->new();

my %body_element;
$body_element{'first'} = 1;
$body_element{'second'} = 2;

push @{ $my_message->message_body }, \%body_element ;

for $e (@{$my_message->message_body})
{
	print "$_=${$e}{$_}\n" for keys%$e;
}

Open in new window

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now