perl引用的一个例子,供初学者参考。

perl引用的一个例子,供初学者参考。

下面的例子演示了perl引用的基本特性,供初学的同好们参考。

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
use strict;

sub add
{
    my ($ref0, $ref1) = @_;
    my $len = @$ref0;
    my $sum = 0;
    for (my $i = 0; $i < $len; $i++) {
        $sum += $ref0->[$i] + $ref1->[$i];
    }
    return $sum;
}

my @arr0 = (1, 1, 1);
my @arr1 = (2, 2, 2);
print add(\@arr0, \@arr1);
# 输出结果为 (1+2) + (1+2) + (1+2) = 9

my $ref0 = [1, 1, 1];
my $ref1 = [3, 3, 3];
print add($ref0, $ref1);
# 输出结果为 (1+3) + (1+3) + (1+3) = 12

perl区分值类型和引用类型,传递参数时使用的是按值传递,所以代码和java/python有很大的不同。

perl中函数的参数应该是别名


QUOTE:
原帖由 gawk 于 2008-6-24 13:09 发表
perl中函数的参数应该是别名

在perl中,参数传递和赋值都是值拷贝,以下是一个例子

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl

@arr1 = (1, 2, 3);
@arr2 = @arr1;  
push @arr2, 4;

$len1 = @arr1;
$len2 = @arr2;
print "len1 = $len1, len2 = $len2\n";
# 输出结果: len1 = 3, len2 = 4

那你在函数中修改一下传递的参数看看
然后在函数调用后再打印一下参数看看

下面这段话摘自perldoc perlsub中
Any arguments passed in show up in the array @_. Therefore, if you
called a function with two arguments, those would be stored in $_[0] and
$_[1]. The array @_ is a local array, but its elements are aliases for
the actual scalar parameters. In particular, if an element $_[0] is
updated, the corresponding argument is updated (or an error occurs if it
is not updatable). If an argument is an array or hash element which did
not exist when the function was called, that element is created only
when (and if) it is modified or a reference to it is taken. (Some
earlier versions of Perl created the element whether or not the element
was assigned to.) Assigning to the whole array @_ removes that aliasing,
and does not update any arguments.

引用的时候的确要小心,函数引用的时候最好加上"&".