Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re^3: print array of hashes

by dmlond (Acolyte)
on Apr 22, 2010 at 20:18 UTC ( #836338=note: print w/ replies, xml ) Need Help??

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);
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;
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:

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:
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).

Comment on Re^3: print array of hashes
Select or Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://836338]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2015-10-07 18:45 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (197 votes), past polls