As to pass list into a subroutine, you specify the subroutine's name and then supply the list to it:
test_subroutine( 'item1', 'item2' );
test_subroutine 'item1', 'item2'; # same
Internally Perl makes aliases to those arguments and put them into the array @_
which is available within the subroutine:
@_ = ( 'item1', 'item2' ); # Done internally by perl
You access subroutine arguments like this:
sub test_subroutine {
print $_[0]; # item1
print $_[1]; # item2
}
Aliasing gives you the ability to change the original value of argument passed to subroutine:
sub test_subroutine {
$_[0] += 2;
}
my $x = 7;
test_subroutine( $x );
print $x; # 9
To prevent inadvertent changes of original values passed into your subroutine, you should copy them:
sub test_subroutine {
my( $copy_arg1, $copy_arg2 ) = @_;
$copy_arg1 += 2;
}
my $x = 7;
test_subroutine $x; # in this case $copy_arg2 will have `undef` value
print $x; # 7
To test how many arguments were passed into the subroutine, check the size of @_
sub test_subroutine {
print scalar @_, ' argument(s) passed into subroutine';
}
If you pass array arguments into a subroutine they all will be flattened:
my @x = ( 1, 2, 3 );
my @y = qw/ a b c /; # ( 'a', 'b', 'c' )
test_some_subroutine @x, 'hi', @y; # 7 argument(s) passed into subroutine
# @_ = ( 1, 2, 3, 'hi', 'a', 'b', 'c' ) # Done internally for this call
If your test_some_subroutine
contains the statement $_[4] = 'd'
, for the above call it will cause $y[0]
to have value d
afterwards:
print "@y"; # d b c