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