我正在阅读Intermediate Perl书,在Chapt10中有这段代码.我添加了一些打印语句,但核心逻辑没有被触及.
#!/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";
}
Run Code Online (Sandbox Code Playgroud)
当我检查Dumper输出然后检查@sorted_positions阵列时,它正在打印
$VAR1 = [
5,
0,
3,
4,
2,
1
];
Run Code Online (Sandbox Code Playgroud)
这对我来说很有意义,但对于@ranks阵列来说它是打印的
$VAR1 = [
2,
6,
5,
3,
4,
1
];
Run Code Online (Sandbox Code Playgroud)
我无法理解这条线正在做什么.
@ranks[@sorted_positions] = ( 1 .. @sorted_positions );
Run Code Online (Sandbox Code Playgroud)
我能够理解输出对程序的意义,但是不能理解输出是如何产生的,即perl在该语句中究竟做了什么.
这条线:
@ranks[@sorted_positions] = ( 1 .. @sorted_positions );
Run Code Online (Sandbox Code Playgroud)
相当于:
@ranks[5,0,3,4,2,1] = (1,2,3,4,5,6);
Run Code Online (Sandbox Code Playgroud)
这相当于:
$ranks[5] = 1;
$ranks[0] = 2;
$ranks[3] = 3;
$ranks[4] = 4;
$ranks[2] = 5;
$ranks[1] = 6;
Run Code Online (Sandbox Code Playgroud)
这个例子是使用slices其在记录perldata手册页.