Perl Programming Page 2 - Variables and Arguments in Perl |
Sometimes we want to pass things other than an ordinary list of scalars, so it’s important to understand how passing arguments works. Function Arguments Passed by Reference An important thing to know about how Perl passes arguments into functions is that arguments are passed by reference, not by value. This is illustrated in the following example: #!/usr/bin/perl -w use strict; my $var = 10; sub change_var { First,$varis assigned 10 and then printed. Then,$varis passed into the functionchange_var(). This function prints the value of$_[0], increments it, then prints it again. The important line of code in this function is ++$_[0]; Since the arguments to the function are passed in through the array@_, to access the zeroth argument of the array we use the syntax$_[0]—this function prints it, increments it, then prints it again. The important thing to note about this code is that since$varis passed into the function by reference, when$_[0]is incremented, Perl actually increments the argument passed in,$var, from 10 to 11. After the function call, the program then prints the resulting value of$var, which is now 11. Executing the code proves this: $ perl byref1.pl The fact that Perl passes arguments by reference is not in itself a bad thing, but it can be if you are not expecting it. Having functions modify arguments when we don’t want them to can create hard-to-find bugs. There is a very simple way to ensure that our functions don’t modify their arguments—simply copy them intomy() variables as shown in this example: #!/usr/bin/perl -w use strict; my $var = 10; print "in change_var() before: $v\n"; The big change here is the first line ofchange_var(): my($v) = @_; This copies the zeroth element of@_, or$_[0], into$v. As mentioned before and as indicated by the comment, we could have written this as my $v = shift; since theshift()function shifts@_by default if invoked within a function (recall also that ifshift()is invoked outside a function it shifts@ARGVby default). Now, since the argument is copied into$v, when we increment it with ++$v; it increments the copy within the function; it does not increment$var. Executing the program proves this: $ perl byref2.pl
blog comments powered by Disqus |
|
|
|
|
|
|
|