shivams shivams - 6 months ago 8
Perl Question

Please explain perl statement

I am reading Intermediate Perl book and in Chapt10 there is this code. I added few print statements but core logic is untouched.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @input = qw(Gilligan Skipper Professor Ginger Mary Ann);
my @sorted_positions = sort { $input[$a] cmp $input[$b] } 0 .. $#input;
print Dumper( \@sorted_positions );
my @ranks;
@ranks[@sorted_positions] = ( 1 .. @sorted_positions );
print Dumper( \@ranks );
foreach ( 0 .. $#ranks ) {
print "$input[$_] sorts into position $ranks[$_]\n";
}


When i check the Dumper output then for
@sorted_positions
array it is printing

$VAR1 = [
5,
0,
3,
4,
2,
1
];


which make sense to me but for
@ranks
array it is printing

$VAR1 = [
2,
6,
5,
3,
4,
1
];


I am unable to understand what this line is doing.

@ranks[@sorted_positions] = ( 1 .. @sorted_positions );


I am able understand what output means in reference to the program but not able to understand how that output is coming i.e. what exactly is perl doing inside that statement.

Answer

The line:

@ranks[@sorted_positions] = ( 1 .. @sorted_positions );

is equivalent to:

@ranks[5,0,3,4,2,1] = (1,2,3,4,5,6);

which is equivalent to:

$ranks[5] = 1;
$ranks[0] = 2;
$ranks[3] = 3;
$ranks[4] = 4;
$ranks[2] = 5;
$ranks[1] = 6;

The example is using slices which are documented in the perldata man page.