perl sub return 的作用

时间:2025-04-20 14:07:19

test_1.pl

#/usr/bin/perl -w

use strict;

print add(1,2),"\n";

sub add {
my ($x,$y) = @_; return $x + $y; # When Perl reaches any return statement it will exit the subroutine at that point.
print "Hello World\n";
}

perl test_1.pl # 3

test_2.pl

#/usr/bin/perl -w

use strict;

print add(1,2),"\n";

sub add {
my ($x,$y) = @_; $x + $y;
print "Hello World\n";
}

perl test_2.pl # Hello World 和 1,还有报错(默认 return sub 中的最后一行;print add(1,2) 则打印出"1")