I usually prefer to receive subroutine arguments with:
because it lets me add or remove arguments easily. The one trick is that, even with a single parameter, you can't remove the parentheses on the left side of the assignment, because it would use @_ in scalar context instead!my ($var1, $var2, $parray) = @_;
In your original code, you've omitted the '$' sigil on your variables, which you need to supply.
Also, note that you can only pass a single array (as the last argument), because passing more than 1 will cause all arrays to be "flattened" into a single array. If that isn't what you want (ie. if you need to pass more than 1), you can use references (I usually prepend 'p' to a variable used as a pointer/reference, like as parray):
sub format_output { my ($var1, $var2, $parray1, $parray2) = @_; # One way to iterate through an array foreach (@$parray1) { print "The next item in the array is $_\n"; } # Another way to iterate through an array for (my $i = 0; $i < @$parray2; $i++) { printf "Array item #%d = %s\n", $i+1, $parray2->[$i]; } }
In reply to Re: Help with scalar values and array as arguments to function
by liverpole
in thread Help with scalar values and array as arguments to function
by unixhome
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |