accessing hash values with %hash->{foo} ?

P

Paul Lalli

I ran across this bizarreness while cleaning up someone else's old
code. A short-but-complete script to demonstrate:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %hash;
%hash->{alpha} = 'one';
%hash->{beta} = 'two';

print Dumper(\%hash);
__END__

$VAR1 = {
'beta' => 'two',
'alpha' => 'one'
};


Why does this work? I cannot seem to find any reference to this
alternate hash syntax of using the % sigil and an arrow to access the
values of a plain hash. I made cursory examinations of perldata and
perlref, but nothing jumped out at me.

Interestingly, running this through -MO=Deparse gives the following
output:
my %hash;
$hash{'alpha'} = 'one';
$hash{'beta'} = 'two';
print Dumper(\%hash);

which seems to suggest that the interpeter is allowing %hash->{foo} to
be syntactic sugar for $hash{foo}.

Does anyone know of a reason for this, or of a documentation that
mentions it?

(This is perl, v5.6.1 built for sun4-solaris)

Thank you,
Paul Lalli
 
R

Robert Sedlacek

Paul Lalli said:
which seems to suggest that the interpeter is allowing %hash->{foo} to
be syntactic sugar for $hash{foo}.

Does anyone know of a reason for this, or of a documentation that
mentions it?

Can't give you that, but JFYI:

phaylon@gaia:~/perl/plague> perl -wle'my %foo = ( bar => 23 ); print
%foo->{ bar }'
Using a hash as a reference is deprecated at -e line 1.
23
phaylon@gaia:~/perl/plague> perl -v

This is perl, v5.8.7 built for i686-linux-thread-multi
...


p
 
B

Brian McCauley

Paul said:
I ran across this bizarreness while cleaning up someone else's old
code. A short-but-complete script to demonstrate:
Excellent!

%hash->{alpha} = 'one';
Why does this work?

It's a bug in the compiler, but becase it does no real harm and there's
bad code out there exlpoiting it, it's not been fixed. (Actually in
earlier versions of Perl it did do harm IIRC, it corrupted the ref
count).
... seems to suggest that the interpeter is allowing %hash->{foo} to
be syntactic sugar for $hash{foo}.

"Sugar" would not be the word I'd use. Bitrex perhaps?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top