Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Load 2 Dimensional Array 2

Status
Not open for further replies.

dkyrtata

Programmer
Aug 13, 2010
107
0
0
CA
This is a simplified example. I want initialize the array in one step:

Code:
$i++;
$a[$i][0] = "a"
$a[$i][1] = "b";

I thought this would work:

Code:
@a[$i][0..1] = ("a","b")

Closer to my real life scenario, I am actually trying to load the array with a split function so that row $i contains 4 columns like this:

Code:
$letters="a,b,c,d"; # There could be any number of letters in the string
$i++;

@a[$i][] = split(",", $letters);







 
I believe the correct way would be:

Perl:
$a[$i] = [ [COLOR=#FF0000]split[/color]([COLOR=#808080]","[/color], $letters) ];

The way multidimensional arrays are implemented in Perl is using an array of array references. $a[0] is a reference to an array containing $a[0][0], $a[0][1], ....

The $array[index1][index2] syntax is just a convenient shorthand for $array[index1]->[index2].

See "Making References" section 2 on perldoc perlref and especially the "Arrow Rule" section on perldoc perlreftut for more info.

Annihilannic
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
Annihilannic

Your example worked. I have given you a star for your solution. Thanks.

PS. Annihilannic, just to get off topic, I am still working on the DBI/DBD problem, but the two key people involved have gone or are going on vacation for the next 4 weeks. Unbelievable timing.
 
How would I now get the number of columns in $a[$i]?

This does not work:

Code:
$numCol = scalar(@a[$i]);
 
Feherke

That worked and it is what I eventually figured out too. But then I wondered how to get the last element of the array using this syntax:

$#a

I often use that instead of scalar(@a)-1



 
One way:
Code:
my @AoA = ([0,1,2], [10, 11]);
print join(" ", $#AoA, $#{$AoA[0]}, $#{$AoA[1]}), "\n";
 
I assume you mean the last element of the "subarray", since $#a works as normal for the outer array? In which case, this should work:

Perl:
$[COLOR=#006600]#{$a[$i]}[/color]

Annihilannic
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
Yes, Annihilannic got it right. That is the last used position of the sub-array within $a[$i].

Thanks again!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top