zecat has asked for the wisdom of the Perl Monks concerning the following question:

Spent the night trying to figure out why the braces subroutine works with dereferencing with braces and the no_braces subroutine halts on execution with the error, "Not an ARRAY reference." Could anyone give an explanation why Perl is preferring the dereferencing with braces and throwing a run time error when they are not included? Tried searching around and people seem to treat both methods as being synonymous. Thanks!
#!/usr/bin/perl use strict; use warnings; my @a1 = qq/one two three four five/; my @a2 = qq/six seven eight nine ten/; my %hash; $hash{key_1} = \@a1; $hash{key_2} = \@a2; braces(\%hash); no_braces(\%hash); sub braces { my $hash_ref = shift; foreach my $key (keys %$hash_ref) { foreach my $value (@{$hash_ref->{$key}}) { #Curly braces print "Key: $key, Value: $value\n"; } } } sub no_braces { my $hash_ref = shift; foreach my $key (keys %$hash_ref) { foreach my $value (@$hash_ref->{$key}) { #No curly braces print "Key: $key, Value: $value\n"; } } }

Replies are listed 'Best First'.
Re: Dereferencing of an arrayref within a hashref
by LanX (Saint) on Feb 17, 2015 at 08:51 UTC
    Precedence!

    That's the effect of no braces

    @{$hash_ref}->{$key}

    which is obviously wrong.

    Cheers Rolf

    PS: Je suis Charlie!

Re: Dereferencing of an arrayref within a hashref
by Not_a_Number (Prior) on Feb 17, 2015 at 09:20 UTC
    my @a1 = qq/one two three four five/;

    This probably isn't doing what you think it's doing: it creates a single string* 'one two three four five'.

    To create a five-element array, use qw instead of qq.

    * Update: and asssigns it to $a1[0].