Perl-Arrays

Perl-Arrays


1.在利用数组的下标时注意数组的长度,比如下面的例子:
@name = qw(fred betty barney dino wilma pebbles bamm-bamm);
print "The name is @name\n";
chmod(@index = <STDIN>);
#######################
#######################
#print the content of index
#$vari = pop (@index);
$a=@index;#获取数组的大小;
print "The value of a is $a\n";
$vari_1 = 0;
########################
[color=red]while($vari_1 <= $a){[/color]print "@index[$vari_1]" . " " ."@name[@index[$vari_1]]\n";
$vari_1 += 1;
}

输入:
3
3
4
4
2
2
输出
3
dino
3
dino
4
wilma
4
wilma
2
barney
2
barney
fred

最后一个"fred"为何也会输出??

改代码:
[color=red]while($vari_1 < $a){[/color]print "@index[$vari_1]" . " " ."@name[@index[$vari_1]]\n";
$vari_1 += 1;
}

输入:
3
3
4
4
2
2
输出
3
dino
3
dino
4
wilma
4
wilma
2
barney
2
barney
当索引超出数组大小时,Perl默认赋值为undef 即为0。
所以第一段代码会输出fred.


2.列表直接量
(1..100)  #100个整数构成的列表
(1,2,3)   #1 2 3构成的列表
比如:求1-1000的和
my @fred=(1..1000);#这里是重点
my $fred_total = total(@fred);
print "The total of \@fred is $fred_total.\n";
print "Enter some numbers on separate lines:";
sub total{
	my $vari_total = 0;
foreach(@_){
	$vari_total += $_;
	#print "$_\n";
}
$vari_total;
}

输出结果:500500

你可能感兴趣的:(C++,c,C#,perl)