Forum Moderators: coopster & phranque

Message Too Old, No Replies

Arrays inside arrays.

Perl seems to hate these...

         

adni18

11:58 pm on Jan 12, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi. I need to make an array of arrays in perl, but for some reason it doesn't want to access the individual parts of the array as individual arrays. Example:

@servers=(
(0,5)
(1,6)
(2,7)
);

what I want to be able to do is call $servers[0][1] and have it return 5. But for whatever reason, $servers[1] returns 5, and $servers[0][1] returns nothing. Any idea how to fix this? Thanks!

perl_diver

12:17 am on Jan 13, 2006 (gmt 0)

10+ Year Member



you just have the syntax wrong:

@servers=(
[0,5],
[1,6],
[2,7]
);

anonymous arrays are created with square brackets, not parenthesis. You may want to read up on perl data structures:

[perldoc.perl.org...]

and maybe references:

[perldoc.perl.org...]

zCat

12:30 am on Jan 13, 2006 (gmt 0)

10+ Year Member




@servers=(
(0,5)
(1,6)
(2,7)
);

as an addendum to perl_diver's reply: what is happening in the original code is that Perl is "flattening out" the bracketed numbers inside the outer parentheses, so effectively you are writing


@servers=(0,5,1,6,2,7);

adni18

2:04 am on Jan 13, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks guys!

perl_diver

3:15 am on Jan 13, 2006 (gmt 0)

10+ Year Member



zCat has a good point, but actually this code isn't valid and will not compile:

@servers=(
(0,5)
(1,6)
(2,7)
);

the below code will create a flattend list and is what I assumed you must be using since your code did seem to run:

@servers=(
(0,5),
(1,6),
(2,7)
);