You can only pass a list of scalars to a subroutine. Arrays will automatically get flattened into a list:
mysub(@a);
is the same thing as
mysub($a[0], $a[1], $a[2], ...);
For example,
sub sortArray { return sort @_; } my @a = ('e', 'd', 'c', 'b', 'a'); my @sorted = sortArray(@a); print("@sorted\n"); # a b c d e # Same thing. my @sorted = sortArray('e', 'd', 'c', 'b', 'a'); print("@sorted\n"); # a b c d e
If you want to modify the array, you can pass a reference to the array to the subroutine.
sub sortArray { my ($ar) = @_; @$ar = sort @$ar; } my @a = qw( e d c b a ); sortArray(\@a); print("@a\n"); # a b c d e
Some references on references:
Update: Added reference links.
Update: Converted first example to sort its arguments.
In reply to Re: HOW Can I pass the array into my subroutine?
by ikegami
in thread HOW Can I pass the array into my subroutine?
by snowsky
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |