http://www.perlmonks.org?node_id=836338


in reply to Re^2: print array of hashes
in thread print array of hashes

There are a couple of things going on here.

First, you have the difference between:

$val = (EXPRESSION);
and
$val = EXPRESSION;
Here the parentheses act like they do in basic math, so, in this case, the two operations are identical.

Next you have the difference between:

scalar ARGS;
and
scalar(ARGS);
For many perl functions (such as scalar), the parentheses surrounding the arguments are optional. It often reads more like a natural human sentence if you omit them, but often it is better to explicitly include them if the resulting statement does not read well as a natural human sentence.

You might also want to know what @{EXPRESSION} means. This is how to dereference an array reference in perl. If $val holds a reference to an array (e.g. it does not hold the array itself), then @{$val} returns the actual array. Similarly you can use %{$val} to dereference the hash referenced by $val, ${$val} to dereference the scalar referenced by $val, and &{$val} to dereference the subroutine referenced by $val, with @{$val}(ARGS) if you need to pass arguments.

Finally, there is the difference between:

$rec[0]{kids}
and
$rec[0]->{kids}
Each element in the @rec array is itself a reference to a hash. Perl provides these two ways to access the scalar held as a value in a hashref, which only differ in the use of the '->' operator. I recommend always using the '->' operator, which explicitly means 'the thing referenced by'. It is much more self documenting. $rec[0]->{kids} is the value keyed to 'kids' in the hash referenced by $rec[0]. Similarly, $array_ref->[0] is the first element in the array referenced by $array_ref, and $code_ref->() is the subroutine referenced by $code_ref. Also, $code_ref->(ARGS) is much more pretty than @{$code_ref}(ARGS). When you get into multidimensional data structures, the '->' can be very helpful. Compare the identically functioning:
${$aref}[0]{kids}[0]{first_name}
and
$aref->[0]->{kids}->[0]->{first_name}
The last one is much more self-documenting, and really starts to look more like an object (which also uses '->' for attributes and methods, which should give you the impression that it is pretty powerful magic).