Perl Programming Invoking Perl Subroutines and Functions |
Invoking a Subroutine The conventional way to invoke a function is to follow the function name with parentheses. This invokes the example_subroutine()function: example_subroutine(); If the function takes arguments (more on passing arguments later in this chapter), then drop them within the parentheses: example_subroutine('Perl is', 'my favorite', $language); Let’s look at a complete example. It’s traditional for programs to tell you their version and name either when they start up or when you ask them with a special option. It’s also convenient to put the code that prints this information into a subroutine to get it out of the way. Let’s take a recognizable program and update it for this traditional practice. Here’s what we started with, version 1: #!/usr/bin/perl -w print "Hello, world!\n"; And here it is with strict mode turned on and version information: #!/usr/bin/perl -w use strict; sub version { my $option = shift; # defaults to shifting @ARGV version() if $option eq "-v" or $option eq "--version"; print "Hello, world.\n"; Now, we’re starting to look like a real utility: $ perl hello2.pl -v The first thing we see inhello2.plis the definition of theversion()function: sub version { It’s a simple block of code that calls theprint()function. It didn’t have to—it could have done anything. Any code that’s valid in the main program is valid inside a subroutine, including calling other functions. We call this block the body of the subroutine, just like we had the body of a loop; similarly, it stretches from the open curly brace after the subroutine name to the matching closing curly brace. Now that we’ve defined it, we can use it. We invoke the function withversion(), and Perl runs that block of code, albeit with the proviso we’ve added the right flag on the command line. version() if $option eq "-v" or $option eq "--version"; When it’s finished executingversion(), it comes back and carries on with the next statement: print "Hello, world.\n"; No doubt version 3 will address the warnings that Perl gives if you call this program without appending-vor
blog comments powered by Disqus |
|
|
|
|
|
|
|