foo(1,2,3,4);
sub foo {
my (@args) = @_; # now @args holds a _copy_ of all the arguments
}
this extends to any and all subroutine argument handling in perl - the only way to get a hold of arguments is to directly or indirectly read from the @_ array. shift() and pop() without further arguments do this implicitly:
sub foo {
my $first = shift; # get the first argument and remove it from @_;
my $last = pop; # get the last argument and remove it from @_;
}
Note that your code above does not do anything with the supplied arguments, it just uses the variables as supplied in the global scope. that means that when the variables are modified in the subroutine, that also modifies the variables in the global scope and in the recursive calls, since they are all the same variable.
Note also that this code:
my $i = 1;
inc($i);
sub inc {
$i++; #note: $i is not declared and read from @_
}
does not do the same as:
my $i = 1;
inc($i);
sub inc {
my $i = shift; # declare and read $i from @_
$i++;
}
In the first example, the outer-scope $i is increased, while in the second example only the $i local to the inc() sub is increased. There's lots of pretty subtle and interesting stuff going on in this simple example. You might start by reading perlsub and/or searching for lexical variables and closures here on perlmonks.
|