Perl Basics   «Prev 

Using Perl Hash Reference

Some Perl operators,
  1. each or
  2. keys
require a hash as an argument. In order to use a dereferenced reference (for example, $hashref->{COUPLES}) in these contexts you must enclose the reference in curly brackets so that the syntax is not ambiguous.

In other words, the expression:
$hashref->{OTHERS}

is a reference to an anonymous hash.
The expression:
%$hashref->{OTHERS}

proably will not do what you expect, because the % binds to the $ and tries to use the hash pointed to by hashref, which is not a reference.
The only way to use a hash operator in this context is to bind the dereference in a block, and then use the hash designator (%) like this:
%{$hashref->{OTHERS}}

which looks more complicated than it is. Just think of the curly brackets as parenthesis for syntax, and you will be fine.
This allows you to do something like:


foreach$i (keys %{$hashref->{OTHERS}}){
	print"$i, $hashref->{OTHERS}->{$i}\n";
}

It is often easier and clearer to use an intermediate variable to hold the hash reference like this:
$others = $hashref->{OTHERS};
foreach$i (keys %$others) {
	print"$i, $others->{$i}\n";
}

Anonymous Hashes

Anonymous hashes are similarly easy to create, except you use braces instead of square brackets:
$hash = { 'Man' => 'Bill',
'Woman' => 'Mary,
'Dog' => 'Ben'
};


The same arguments for the anonymous array composer also apply here. You can use any normal element such as
  1. a string literal (as in the preceding code),
  2. an expression, or
  3. a variable
to create the structure in question. Also note that the same principles for arrays of arrays can be applied to hashes, too, but we will cover the specifics of nested hash and array structures later in this module.
Note that this composition procedure only works when Perl is expecting a term— that is, usually when making an assignment or expecting a hash or reference as an element. Braces are not only used for creating anonymous hashes, but they are also responsible for selecting hash subscript elements and for defining blocks within Perl. This means you must occasionally explicitly specify the creation of an anonymous hash reference by preceding the hash creator with a + or return:
$envref = +{ %ENV };
sub dupeenv{ return { %ENV } };