Accessing elements in hash of hash of arrays in perl

my %PlannedPerWeek = (
                    September => {
                            Week1 => [80, 23, 199, 45, 19, 36],
                            Week2 => [78, 21, 195, 43, 18, 36],
                            Week3 => [76, 19, 191, 41, 17, 36],
                            Week4 => [74, 17, 187, 39, 16, 36],
                    }
    );

I have the above hash of hash of arrays in a perl prog. How do I access element say '199' from the above data structure.

Answers


It's rather straightforward. The first one is a hash, so you don't need to dereference it. Every following 'container' inside your data structure is a reference, so you can use the -> operator to dereference that structure. Stuff that is inside curly brackets {} is a hash (key/value-pairs) reference and needs curlies to deref, while the stuff inside square brackets [] is an array reference and again needs square brackets do deref.

Now it's really just lining up the things and counting to 3:

print $PlannedPerWeek{'September'}->{'Week1'}->[2];
                                               ^---- 3rd array ref element
                                    ^--------------- hashref key 'Week1'
                      ^----------------------------- hash key 'September'

You can also leave out the arrows and just go:

print $PlannedPerWeek{'September'}{'Week3'}[2];

You should read perlreftut, which says:

In between two subscripts, the arrow is optional.


Need Your Help

JSF ajax and custom converter

java ajax jsf converter managed-bean

I have a problem with may AJAX on JSF page. He doesn't call the bean method. Converter works and returns a correct object, but bean method doesn't call.

Rails: how to represent user follow user relationship?

ruby-on-rails-3 activerecord model-associations

I have a class User and I would like to implement the follow relation (as in twitter).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.