Reputation: 55
My code:
my $aaa = "abc";
sub myp{
print "$_";
}
myp($aaa);
I hope myp can print the argument it get. But it said Use of uninitialized value $_ in string at ./arg line 17.
Upvotes: 0
Views: 82
Reputation: 540
I usually do something like:
my $first_arg = shift @_;
my $second_arg = shift @_;
You can also use the method of the other response:
my ($first_arg, $second_arg) = @_;
But be careful saying:
my $first_arg = @_;
Since you will get the number of arguments passed to the subroutine.
When you refer to $_
you are referencing the default string variable, you probably want in this case to refer @_
, if you want to get a specific argument, you must say $_[narg]
, be also careful passing arrays to subroutines if you do:
some_sub(@myarray);
You will pass the entire array as it was the argument list, instead you should say:
some_sub(\@myarray);
Upvotes: 1
Reputation:
The arguments to a subroutine in Perl are passed in the @_
array. This is not the same as the $_
variable.
A common idiom is to "unpack" these arguments in the first line of a function, e.g.
sub example {
my ($arg1, $arg2) = @_;
print "$arg1 and $arg2";
}
It's also possible to refer to arguments directly as elements of @_
, e.g. as $_[0]
, but this is much harder to read and as such is best avoided.
Upvotes: 5