I am trying to "push" onto an anonymous 3 element 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 element 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!
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 "))"
CodePudding user response:
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;