Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Hash of Hash

by davies (Parson)
on Feb 16, 2014 at 16:29 UTC ( #1075096=note: print w/replies, xml ) Need Help??

in reply to Hash of Hash

Looking at the book, I see that chapter 6 is on references. This is not the simplest area of Perl, but it's worth understanding because of its power. The title of your node makes me think that you may be slightly confused. In your first code snippet, $sales is a reference to an anonymous hash of hashes of arrays. It's not a simple hash of hashes (or HoH). One of the monastery's most highly rated tutorials is References quick reference, which may help you.

To try to explain the second snippet in more detail, let's start with the first line: my $commissions = $sales->{tuesday}{jim}. This creates a reference to an array, the array being the element of the anonymous HoH containing Jim's commissions on Tuesday.

The next line gives the number of elements in the array referenced. If you understand that $commissions is an array reference, References quick reference will explain that using the combined @$ sigils will derefer the reference, so that you are returning the array itself. However, you are returning it in "scalar context". Context is something else that often confuses people, me included (just look through my writeups). In scalar context, this returns the number of elements in an array. The latest versions of Perl have a function that makes this explicit, so you might say my $elements = scalar(@array);.

Compare this to the use of @$commissions in the fourth line of your second snippet. Here, the array is being used in list context, meaning that each element of the array will, in turn, be put into the default variable $_. Line 5 will add them to $total, which was initialised to 0 in line 3.

Hope this helps. I also hope that my understanding is correct. If anyone says I've got it wrong, believe them.


John Davies

Replies are listed 'Best First'.
Re^2: Hash of Hash
by AnomalousMonk (Chancellor) on Feb 16, 2014 at 16:55 UTC
    However, you are returning it in "scalar context". Context is ...

    IvanAK: For a Tutorial on context, see Context tutorial, but also pay attention to the discussions in the replies thereto, and also to the links therefrom. (Update: And, in general, see the many Tutorials on this site.)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1075096]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2018-03-25 02:21 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (299 votes). Check out past polls.