from perlsub, 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, but below code block output are not expected, why?
sub swap_1 { (@_) = reverse(@_); } sub swap_2 { my @item = reverse(@_); (@_) = ($item[0], $item[1]); print "##swap2_1: $item[0]\n"; print "##swap2_1: $item[1]\n"; print "-------------\n"; $_[0] = $item[0]; $_[1] = $item[1]; print "##swap2_2: $_[0]\n"; print "##swap2_2: $_[1]\n"; print "-------------\n"; } sub swap_3 { $_[0] = "AAA"; $_[1] = "BBB"; } my $one = "I am one"; my $two = "I am two"; swap_1($one,$two); print "one is '$one'\n"; print "two is '$two'\n"; print "-------------\n"; swap_2($one,$two); print "one is '$one'\n"; print "two is '$two'\n"; print "-------------\n"; swap_3($one,$two); print "one is '$one'\n"; print "two is '$two'\n"; print "-------------\n";
I expect swap_1, swap_2 can do the swap work, but obviously, I am wrong. but swap_3 is expected
below are the output
one is 'I am one' two is 'I am two' ------------- ##swap2_1: I am two ##swap2_1: I am one ------------- ##swap2_2: I am two ##swap2_2: I am one ------------- one is 'I am one' two is 'I am two' ------------- one is 'AAA' two is 'BBB' -------------
In reply to Accessing Arguments inside Subroutines via @_ by citi2015
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |