Perl Programming Page 5 - Perl 101 (Part 5) - Sub-Zero Code |
Now, if you've been paying attention, you've seen how subroutines can help you segregate blocks of code, and use the same piece of code over and over again, thereby eliminating unnecessary duplication. But this is just the tip of the iceberg... The subroutines you've seen thus far are largely static, in that the variables they use are already defined. But it's also possible to pass variables to a subroutine from the main program - these variables are called "arguments", and they add a whole new level of power and flexibility to your code. Consider the following simple example: A few words of explanation here: You're already familiar with the special Perl array @ARGV, which contains parameters passed to the Perl program on the command line. Well, Perl also has a variable named @_, which contains arguments passed to a subroutine, and which is available to the subroutine when it is invoked. The value of each element of the array can be accessed using standard scalar notation - $_[0] for the first element, $_[1] for the second element, and so on. In the example above, once the &add_two_numbers subroutine is invoked with the numbers 3 and 5, the numbers are transferred to the @_ variable, and are then accessed using standard scalar notation within the subroutine. Once the addition has been performed, the result is returned to the main program, and displayed on the screen via the print() statement. Note the manner in which arguments are passed to the subroutine, enclosed within a pair of parentheses. How about something a little more useful? Let's go back a couple of pages, and consider the &change_temp subroutine we've defined: Now, suppose we alter this to accept the temperature in Celsius from the main program, and return the temperature in Fahrenheit. And here's what it would look like: Enter temperature in Celsius45 45 Celsius is 113 Fahrenheit Take it one step further - how about allowing the user to specify the temperature to be converted on the command line itself? If you saved this program as "convert_temp.pl", and ran it like this you'd see 35 Celsius is 95 Fahrenheit The above example also neatly demonstrates the relationship between @ARGV and @_ - the temperature entered on the command line first goes into the @ARGV variable, and is then passed to the subroutine via the @_ variable. Remember that the @_ variable is only available within the scope of a specific subroutine. This article copyright Melonfire 2000. All rights reserved.
blog comments powered by Disqus |