Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to push to an anonymous 3 dimensional array referenced in a hash

I am trying to "push" onto an anonymous 3 dimensional array whose reference is stored in a hash:

my %messages;
my $to = "To";
... later ...
$messages{$msg_id}{$to} = [ [], [], [] ];

which basically works, because Data::Dumper shows an empty 3 dimensional array.
My problem is I can’t work out how to "push" data onto this anonymous array!

I have tried many things, but realise I am just thrashing about. A couple of examples of my many failures!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my word = "something";
push(@{ $messages{$msg_id}{$to} }->[0], ( $word ));
Can't use an array as a reference at ./hash_array.pl line 53.
my @array = ( word1, word2, word3 );
push(\@{ $messages{$msg_id}{$to} }, ( @array ));
Experimental push on scalar is now forbidden at ./hash_array.pl line 54, near "))"

Any help appreciated!

>Solution :

You just need to move the ->[0] into @{...}.
The first argument of push must be an array, not a reference.
See also: https://perldoc.perl.org/perlref

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %messages;
my $msg_id = 123;
my $to = "To";
$messages{$msg_id}{$to} = [ [], [], [] ];

my $word = "something";
push(@{ $messages{$msg_id}{$to}->[0] }, ( $word ));

print Dumper \%messages;

1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading