perl 函数参数传递与返回值,一

1.参数传递

普通模式:参数中没有数组和哈希

#!/usr/bin/perl -w
use strict;
sub getparameter
{
        my $i;
        for( $i=0;$i<=$#_;$i++)
        {
                print "It's the ";
                print $i+1;
                print " parameter:$_[$i]\n";
        }

}

无论参数有多少个,均能正常传递。

调用函数

&getparameter($first,$second .. $end)

文艺模式:参数中包含数组

还是这个函数,只不过我们传递的参数里包括一个数组

#!/usr/bin/perl -w
use strict;
sub getparameter
{
        my $i;
        for( $i=0;$i<=$#_;$i++)
        {
                print "It's the ";
                print $i+1;
                print " parameter:$_[$i]\n";
        }

}
my @array=("this","is","a","test");
my $variable="this is another test";
#&getparameter(@array,$variable);
&getparameter($variable,@array);

当我们只传入2个参数,一个数组,一个变量,结果是这样 ,变成了5个参数。无论数组在前还是在后,都是显示5个参数。 由此 @_ 会把数组每一个值当做一个参数储存。那我的疑问是perl能否正确的把传递的数组还原成数组而不是单个变量???

It's the 1 parameter:this is another test

It's the 2 parameter:this

It's the 3 parameter:is

It's the 4 parameter:a

It's the 5 parameter:test

那我们换一种方式接受参数:

#!/usr/bin/perl -w
use strict;
sub getparameter
{
        (my @arr,my $var)=@_;
        print  "It's the 1 parameter:@arr\n";
        print "It's the 2 parameter:$var\n";

}
my @array=("this","is","a","test");
my $variable="this is another test";
&getparameter(@array,$variable);

结果令人意外,$variable传递的参数丢失, 同时数组却取得所有参数,相当于把变量归为数组的一个元素。per了接受传递来的数组,会贪婪的把变量变成数组的元素。所以在接受参数传递赋值时,不要把数组放前面。

It's the 1 parameter:this is a test this is another test

Use of uninitialized value in concatenation (.) or string at test2.pl line 7.

It's the 2 parameter:

改成这样就好了:

#!/usr/bin/perl -w
use strict;
sub getparameter
{
        (my $var,my @arr)=@_;
        print "It's the 1 parameter:$var\n";
        print  "Ti's the 2 parameter:@arr\n";

}
my @array=("this","is","a","test");
my $variable="this is another test";
#&getparameter(@array,$variable);
&getparameter($variable,@array);

运行结果:

It's the 1 parameter:this is another test

Ti's the 2 parameter:this is a test

如果要传递2个数组怎么办???

可以采用引用的方式

#!/usr/bin/perl -w
use strict;
sub getparameter
{
        (my $arr1,my $arr2)=@_;
        print "It's the 1 parameter:@$arr1\n";
        print  "Ti's the 2 parameter:@$arr2\n";

}
my @array1=("this","is","a","test");
my @array2=qw/this is another test/;
#&getparameter(@array,$variable);
&getparameter(\@array1,\@array2);

per了使用引用是在变量或数组前加\ ,相当于地址传递

所以运行结果是:

It's the 1 parameter:this is a test

Ti's the 2 parameter:this is another test