perl return和break

时间:2022-06-01 21:09:29
zjzc01:/root/test# cat a3.pl
sub mask {
my $n=shift;
my $j =100;
for ($i = 1;$i <= 5;$i++){
print "\$i is $i\n";
while ($n=$n+1) {
$j++;
print "\$n is $n\n";
if ($n==10){print "\$n---end is $n\n";$n=0;last};
}}
}; &mask(1);
zjzc01:/root/test# perl a3.pl
$i is 1
$n is 2
$n is 3
$n is 4
$n is 5
$n is 6
$n is 7
$n is 8
$n is 9
$n is 10
$n---end is 10
$i is 2
$n is 1
$n is 2
$n is 3
$n is 4
$n is 5
$n is 6
$n is 7
$n is 8
$n is 9
$n is 10
$n---end is 10
$i is 3
$n is 1
$n is 2
$n is 3
$n is 4
$n is 5
$n is 6
$n is 7
$n is 8
$n is 9
$n is 10
$n---end is 10
$i is 4
$n is 1
$n is 2
$n is 3
$n is 4
$n is 5
$n is 6
$n is 7
$n is 8
$n is 9
$n is 10
$n---end is 10
$i is 5
$n is 1
$n is 2
$n is 3
$n is 4
$n is 5
$n is 6
$n is 7
$n is 8
$n is 9
$n is 10
$n---end is 10 last 是退出当前循环 zjzc01:/root/test# cat a3.pl
sub mask {
my $n=shift;
my $j =100;
for ($i = 1;$i <= 5;$i++){
print "\$i is $i\n";
while ($n=$n+1) {
$j++;
print "\$n is $n\n";
if ($n==10){print "\$n---end is $n\n";$n=0;return};
}}
}; &mask(1);
zjzc01:/root/test# perl a3.pl
$i is 1
$n is 2
$n is 3
$n is 4
$n is 5
$n is 6
$n is 7
$n is 8
$n is 9
$n is 10
$n---end is 10 return是退出当前函数 退出循环是break
return是退出函数并返回, 如果函数有返回值,可以将返回值返回