[英]Please explain perl statement
我正在閱讀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";
}
當我檢查Dumper輸出然后檢查@sorted_positions
數組時,它正在打印
$VAR1 = [
5,
0,
3,
4,
2,
1
];
這對我來說很有意義,但對於@ranks
數組來說它是打印的
$VAR1 = [
2,
6,
5,
3,
4,
1
];
我無法理解這條線正在做什么。
@ranks[@sorted_positions] = ( 1 .. @sorted_positions );
我能夠理解輸出對程序的意義,但是不能理解輸出是如何產生的,即perl在該語句中究竟做了什么。
這條線:
@ranks[@sorted_positions] = ( 1 .. @sorted_positions );
相當於:
@ranks[5,0,3,4,2,1] = (1,2,3,4,5,6);
這相當於:
$ranks[5] = 1;
$ranks[0] = 2;
$ranks[3] = 3;
$ranks[4] = 4;
$ranks[2] = 5;
$ranks[1] = 6;
該示例使用了perldata
手冊頁中記錄的slices
。
假設您想要將字符串'x'分配到數組的第一個位置,將'y'分配到第二個位置,將'z'分配到第三個位置。 你可以同時做三個任務,而不是做三個任務;
@array[0,1,2] = ("x", "y", "z");
你不必按順序這樣做;
@array[2,0,1] = ("z", "x", "y"); # same result
所討論的行的右側產生一個以1開頭的數字列表,並以@sorted_positions
表達式返回的整數值結束(由於@sorted_positions
中有6個東西,因此為6) - 即它與...相同 ;
(1,2,3,4,5,6)
所以, 整個陳述與:
@ranks[5,0,3,4,2] = (1,2,3,4,5,6) ;
所以,如果我們只進行一次迭代:
foreach ( 0 .. $#ranks ) {
print "$input[$_] sorts into position $ranks[$_]\n";
}
我們得到;
print "$input[0] sorts into position $ranks[0]\n"
# ie: Gilligan sorts into position 2
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.