傳遞一個參考和修改子程序內的原始變量將這樣來完成:
$text = 'hello';
convert_to_uppercase(\$text); #notice the \ before $text
print $text;
sub convert_to_uppercase { #perl doesn't specify arguments here
### arguments will be in @_, so @_ is now a list like ('hello')
my $ref = shift; #$ref is NOT 'hello'. it's '$text'
### add some output so you can see what's going on:
print 'Variable $ref is: ', $ref, " \n"; #will print some hex number like SCALAR(0xad1d2)
print 'Variable ${$ref} is: ', ${$ref}, " \n"; #will print 'hello'
# Now do what this function is supposed to do:
${$ref} = uc ${$ref}; #it's modifying the original variable, not a copy of it
}
另一種方法是給子程序外部創建的子程序內的返回值並修改變量:
$text = 'hello';
$text = convert_to_uppercase($text); #there's no \ this time
print $text;
sub convert_to_uppercase {
# @_ contains 'hello'
my $input = shift; #$input is 'hello'
return uc $input; #returns 'HELLO'
}
但是convert_to_uppercase例程似乎是多餘的,因爲這就是uc所做的。跳過這一切,只是這樣做:
$text = 'hello';
$text = uc $text;
這個問題可能會有所幫助:http://stackoverflow.com/questions/24063638/if-perl-is-call-by-reference-why-does-this-發生 – AntonH 2014-10-16 22:21:29
非常感謝!我的新問題是:爲什麼($ x1,$ y1)= @_;?如果我這樣做,它會是相同的:** $ x1 = $ _ [0]; $ y1 = $ _ [1]; **?請考慮我對Perl真的很陌生,並感謝您的耐心等待! – gonfer 2014-10-16 23:14:37
是的。 '($ x1,$ y1)= @_;'是一個快捷方式。 – AntonH 2014-10-16 23:27:12