I thought that @_ meant the list passed to the sub, so I used $_ when I passed a single element.
@_ contains the list of arguments for a sub, but you want the first argument of that array, which is $_[0]. $_ is something completely different, as you already know.
There are two common idioms for accessing arguments:
sub foo { my $onlyarg=shift; # @_ is the default argument for shift # more code }
and
sub bar { my ($huey,$dewey,$louie)=@_; # more code }
Of course, you can also write
sub baz { my $onlyarg=$_[0]; # more code }
or
sub moo { my $huey=shift; my $dewey=shift; my $louie=shift; # more code }
or even
sub ohnononononopleaseno { my $huey=$_[0]; my $dewey=$_[1]; my $louie=$_[2]; # more code }
But that is uncommon and has some strange accent. Stick with the first two variants. Having only one argument needs no exception, you can use the list assignment even for a single argument, no need for shift:
sub foo2 { my ($onlyarg)=@_; # more code }
Just remember the parentheses, or else $onlyarg will contain the number of arguments, in this case 1. Not what you want.
Alexander
In reply to Re^3: Wrong content of variable passed to sub
by afoken
in thread Wrong content of variable passed to sub
by olafmar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |