%data = (
'digits' => [1, 2, 3],
'letters' => ['a', 'b', 'c']
);
How can I push
'4'
into $data{'digits'}
?
I am new to Perl. Those $
, @
, %
symbols look weird to me; I come from a PHP background.
To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value. When inverted, you end up with a hash that has many values for the same key.
To assign that array to a hash element, you'd use either $b{"x"} = [@a] or $b{"x"} = \@a , depending on what you're trying to do. [@a] makes a new arrayref containing a copy of the current contents of @a . If the contents of @a change after that, it has no effect on $b{x} .
push @{ $data{'digits'} }, 4;
$data{'digits'} returns an array-reference. Put @{} around it to "dereference it". In the same way, %{} will dereference a hash reference, and ${} a scalar reference.
If you need to put something into a hash reference, i.e.
$hashref = { "foo" => "bar" }
You can use either:
${ $hashref }{ "foo2" } = "bar2"
or the arrow-notation:
$hashref->{"foo2"} = "bar2"
In a certain way, think of a reference as the same thing as the name of the variable:
push @{ $arrayref }, 4
push @{ "arrayname" }, 4
push @arrayname , 4
In fact, that's what "soft references" are. If you don't have all the strictnesses turned on, you can literally:
# perl -de 0
DB<1> @a=(1,2,3)
DB<2> $name="a"
DB<3> push @{$name}, 4
DB<4> p @a
1234
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With