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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to create and sort two-dimensional array... 1

Status
Not open for further replies.

programmerhead

Programmer
Sep 15, 2003
6
US
I can't seem to find any helpful documentation on how to create two dimensional arrays in perl and sort them. For instance, I have a script that provides a person's name and a description of them in strings in a for loop. I want to be able to sort an array by the first names, while still retaining their relationship to the descriptions.

for($i=0; $i<10; $i++){
my $temp_name = param('$i_name');
my $temp_descrip = param('$i_descrip');
}

Can anyone help me please?
 
You need to u/s references to do a 2D array. A 2D array is an array of array references. There is much documentation on the subject. Check out

perldoc perldsc
perldoc perllol
perldoc perlref
perldoc perlreftut


If you prefer your documentation on the web:
and search for perldsc, perllol, etc.

To make a 2D array with your names and desriptions as given above and sort it by the name field, you'd do something like this:
Code:
[b]my @arr;[/b]
for($i=0; $i<10; $i++){
  my $temp_name = param('$i_name');
  my $temp_descrip = param('$i_descrip');
  [b]push(@arr, [$temp_name, $temp_descrip]);[/b]
}
[b]for (sort {$a->[0] cmp $b->[0]} @arr) {
  print "[", join(", ", @$_), "]\n";
}[/b]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top