tags:

views:

86

answers:

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

+6  A: 
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
eruciform
A non-hard reference is a symbolic reference.
ysth
+2  A: 
push @{data{'digits'}}, 4;

The @{} makes an array from a reference (data{'digits'} returns an array reference.) Then we use the array we got to push the value 4 onto the array in the hash.

This link helps explain it a little bit.

I use this link for any questions about hashes in Perl.

KLee1
+1  A: 
push @{ $data{digits} }, 4;

The official Perl documentation website has a good tutorial on data structures: perldsc, particularly the Hashes-of-Arrays section.

$, @ and % are known as sigils.

toolic
+2  A: 

For an exotic but very pleasing on the eye option take a look at the autobox::Core CPAN module.

use autobox::Core;

my %data = (
    digits  => [1, 2, 3],
    letters => ['a', 'b', 'c'],
);

$data{digits}->push(4);

$data{digits}->say;   # => 1 2 3 4

/I3az/

draegtun