Xét VD:
Xét VD:
sub
sub add add { {
my $sum = 0 ;
my $sum = 0 ; #tao bien cuc bo $sum va #tao bien cuc bo $sum va
khoi tao gia tri =0
khoi tao gia tri =0
foreach $_ (@_ ) {
foreach $_ (@_ ) {
$sum += $_ ;
$sum += $_ ; #cong tung phan tu#cong tung phan tu
}
}
return $sum;
return $sum; #tra ve ket qua #tra ve ket qua }
}
$a =
$a = addadd(4,5,6) ; (4,5,6) ; #cong 4+5+6 = 15, va #cong 4+5+6 = 15, va
gan cho $a
gan cho $a
33
III.5. Biến cục bộ trong hàm(tt):
sub bigger_than {
sub bigger_than {
my ($n, @values);
my ($n, @values); #tao ra cac bien #tao ra cac bien cuc bo
cuc bo
($n, @values) = @_; ($n, @values) = @_; #khoi tao gia tri #khoi tao gia tri
cho bien cuc bo, thuc chat la lay gia tri tu cac
cho bien cuc bo, thuc chat la lay gia tri tu cac
tham so
tham so
my (@result);
my (@result); #them 1 bien cuc #them 1 bien cuc
bo nua
bo nua
foreach $_ (@values) {
foreach $_ (@values) { #duyet danh sach #duyet danh sach
cac gia tri
cac gia tri
if ($_ > $n) {
if ($_ > $n) { #phan tu nay co gia tri lon #phan tu nay co gia tri lon
hon $n (=50, 100 hay gia tri nao do)
hon $n (=50, 100 hay gia tri nao do)
push (@result, $_) ;push (@result, $_) ; #dua vao danh #dua vao danh sach neu hop le
sach neu hop le
}}
return @result;
return @result; #tra ve ket qua#tra ve ket qua
}
III.5. Biến cục bộ trong hàm(tt):
VD: VD:
@new = bigger_than(100, @list);
@new = bigger_than(100, @list); #tim cac phan tu lon hon 100 trong mang @list #tim cac phan tu lon hon 100 trong mang @list
@this =
@this = bigger_than(5,1,5,15,30);bigger_than(5,1,5,15,30);
#tim cac phan tu lon hon 5 trong danh sach, #tim cac phan tu lon hon 5 trong danh sach,
ket qua la (15, 30) ket qua la (15, 30)
35