in reply to Is this a hash slice?

It's all about the brackets. Where do you have to leave them out, where can you leave them in... and where does it work both ways?

What I didn't realize going into this, is that this is a situation where it works both ways. The following demo clears things up to my satisfaction.

Thanks, brother monks!

use strict; use warnings; use Data::Dumper; #Populate the hash the first way. my @keys = qw(a b c d e f); my %hash; @hash{@keys} = (1,1,1,1,1,1); # first verse. print Dumper(\%hash); #clear %hash. for (keys %hash) { delete $hash{$_}; } print Dumper(\%hash); #Populate the hash the second way, using scalars and arrays. ${hash}{a} = 1; $hash{b} = 1; # proving brackets optional when setting hash values in +$calar mode. @{hash}{('c','d')} = (1,1); @hash{'e','f'} = (1,1); # proving brackets optional when setting hash +values in @rray mode # second verse, same as the first. print Dumper(\%hash);

Replies are listed 'Best First'.
Re^2: Is this a hash slice?
by Roy Johnson (Monsignor) on Apr 01, 2005 at 02:43 UTC
    You never need to put braces around the hash name unless its name is wacky, and I can't figure out how to legally make one so wacky, so let's just ignore that possibility.

    You need braces around a hash reference any time it is not a simple scalar variable and you are not fetching a single element, because the precedence of the dereferencing operators will not DWYM otherwise. You may put braces around a hashref any time you feel like it. And those braces around the hashref are a true BLOCK: you can put any code you like in there, as long as the final result is a hash ref. It's just like a do-block, but the do is implied by the dereferencing.

    To illustrate the precedence considerations:

    my $foo = {a => 1}; # $foo is a hashref print $$foo{a}; # Ok print @$foo{a}; # one-element slice, but ok print $foo->{a}; # Preferred single-element fetch my %bar = (a => {b => 1}); # %bar is a HoH print ${$bar{a}}{b}; # Ok print @{$bar{a}}{b}; # one-element slice, but ok print @$bar{a}{b}; ### syntax error! print $bar{a}{b}; # Preferred single-element fetch
    The syntax error line thinks $bar must be a reference, like $foo was earlier. But it is $bar{a} that is the reference we want to dereference.

    See perldoc perlreftut for a nice statement of the (only 2!) rules for using references.


    Caution: Contents may have been coded under pressure.