Suppose we are designing a series of web pages, and we want to put a line with
our name and email address on the bottom of each of the pages. We could reproduce
the code to write this line each time we need it, but a far better strategy is
to create a function called, say write_email_line
, and then simply call that
function when we need to print the line. In perl, the keyword to inform the
interpreter that you're going to define a function is the word sub
, from the
term subroutine which is basically another name for a function. You follow the
keyword with the name of your function, and finally a block of statements (surrounded
as usual with curly braces), containing the perl statements you wish to have
executed when you call the function. For our simple example, the function might
look like this:
sub write_email_line{ print("<hr><p>Please send comments to"); print(qq{ <a href="mailto:webmaster@mysite.com">webmaster</a><br><hr>}); }Now, when we wish to print the email line, we simply call the function as follows:
write_email_line();In earlier versions of perl, user-written functions were identified by a prefix of an ampersand (
&
). While you still can refer to functions in this
way, it is not necessary.
Such a simple function probably isn't that useful. We could make it more
general by using some variables: $user
for the name of the user to mail to,
and $email
for the name of the email account to use:
sub write_email_line{ print("<hr><p>Please send comments to"); print(qq{ <a href="mailto:$email">$user</a><br><hr>}); }While this provides some extra flexibility, it's far from ideal. If the variable
$user
or $email
are manipulated anywhere else in the program,
or if they represent something other than what we think they should, we'll get
unpredictable results. Similarly, if we change those variables inside the
function they'll have different values when the function returns, which could be very
difficult to track down in the case of a problem. The solution to this problem,
as outlined in the next section, is to pass arguments to the function.