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

1

4 Answers 4

16
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
Sign up to request clarification or add additional context in comments.

1 Comment

A non-hard reference is a symbolic reference.
3
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.

Comments

2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.