Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^3: Creating a unique variable type

by Laurent_R (Parson)
on Mar 26, 2013 at 22:42 UTC ( #1025595=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Creating a unique variable type
in thread Creating a unique variable type

Your are right, you can't really place an array inside another array with Perl, but you can put in an array a reference toward another array. And you can do it in a way that you don't have to be explicit about the existence of a reference, it really looks like a two-dimensional array.

Suppose you want to store in an array the full name and the abbreviated name of each of the months. Your could do this in various syntactic ways as follows:

$month[0][0] = "January"; $month[0][1] = "Jan"; $month[1] = ["February", "Feb"]; push @month, ["March", "Mar"]; push @{$month[3]}, "April"; push @{$month[3]}, "Apr";
If you dump the content of @month under the debugger, you get the following structure:
0 ARRAY(0x20381390) 0 'January' 1 'Jan' 1 ARRAY(0x20381528) 0 'February' 1 'Feb' 2 ARRAY(0x203815d0) 0 'March' 1 'Mar' 3 ARRAY(0x204424d0) 0 'April' 1 'Apr'

The dump shows that the @month array contains 4 references to arrays (the 'ARRAY(0x20381390)' part), and that each of these arrays contain two elements, the month full and short names. And you can just print one element as follows:

print $month[3][1]; # prints "Apr"

So you could almost use all this without even knowing about references. Except that if you don't understand the underlying references, you will not be able to understand what's happening when something goes wrong (say, when the compiler complains about some illegal construct or, worse, when your program is not doing what you want because your data is not quite what you think).

In brief, you can in principle construct an entire program with AoA (or AoH, HoA or HAH) without ever using a syntax that explicitly shows that the top-level array contains in fact references to other (anonymous) arrays. But you still need to know and understand this reference shebang if you are going to use it for anything else than an extremely simple program.


Comment on Re^3: Creating a unique variable type
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2014-09-18 12:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (114 votes), past polls