in reply to Re^9: search and replace strings in different files in a directory (Path::Tiny)
in thread search and replace strings in different files in a directory
Hello PitifulProgrammer,
Why was the subroutine called with 6 passed as an argument. Was this just for demonstrating that not only strings but also numbers can be passed to a sub?
Maybe, I don’t know, I didn’t write the code. ;-)
Could you please clarify why only the first argument $ra is passed an the others remain in the array? Does that mean that arguments to a sub are passed in some kind of for loop?
No, no, no! Perl is not like C, where arguments are passed by value (i.e., as local copies). In Perl, arguments are passed by reference. Specifically, the arguments passed into a subroutine are available within that subroutine in the special array variable @_ (also called @ARG), which contains aliases to the originals.
What this means is that if you call foo($bar, $baz), then within that call to sub foo the variable $_[0], which is the first element of the array @_, is an alias for $bar, and likewise $_[1] is an alias for $baz. So if you change $_[0] within the subroutine, when you return from the subroutine you find that $bar has changed too.
Sometimes this is what you want, but mostly it isn’t. So the usual practice is to make local copies of the arguments before using them. These local copies are not aliases, so changing the local copies has no effect on the originals. There are two ways of creating the local copies:
Within a sub, when shift is used without an explicit argument it automatically shifts @_. For example,
sub foo { my $x = shift; my $y = shift; ...
This removes the first two elements from @_ and makes copies of them in $x and $y, respectively.
Simple assignment:
sub foo { my ($x, $y) = @_; ...
This makes local copies of the first two elements of @_, but @_ itself remains unchanged.
Please see the entry for @_ in perlvar, and study perlsub, especially the third paragraph of the “DESCRIPTION” section.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|