Chris Field
Chris Field

Reputation: 15

Sort command in Perl - Can someone explain what is happening in this script?

new coder here working in Perl. Can someone explain to me what the following portion of the below code is doing? I know that it is performing an alphabetical sort of the elements in array @animals and I think it is then assigning the sorted index values to @idx. I have no idea what the last portion "0 .. $#animals;" is doing. It appears that '..' is the range operator in Perl.

my @idx = sort { 
$animals[$a] cmp $animals[$b] 
} 0 .. $#animals;

Here is the full code:

@animals = (dog,cat,iguana,parakeet,monkey, giraffe);
@diets = (beef,chicken,chickpeas,seeds,bananna,tree);
@age = (7,3,5,2,20,18);

my @idx = sort { 
$animals[$a] cmp $animals[$b] 
} 0 .. $#animals;

@animals = @animals[@idx];
@diets = @diets[@idx];
@age = @age[@idx];

print "@animals\n";
print "@diets\n";
print "@age\n";

Upvotes: 0

Views: 56

Answers (1)

Jim Davis
Jim Davis

Reputation: 5290

$#animals is the index of the last entry in @animals; in your example, that'd be 5.

The range operator takes that 0 .. 5 and expands it to 0, 1, 2, 3, 4, 5.

That list of integers gets passed to sort, which treats them as indexes into @animals and sorts them based on the value in that array.

Incidentally, parallel arrays make a great candidate for some other structure, like an array of hash references.

Upvotes: 4

Related Questions