Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I push an element into an array reference held as a hash value?

Tags:

perl

%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.

like image 531
powerboy Avatar asked Jul 11 '10 00:07

powerboy


People also ask

How do you push an array into a hash?

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.

How do I assign an array to a hash value in Perl?

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} .


1 Answers

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
like image 149
eruciform Avatar answered Sep 19 '22 14:09

eruciform