25.9. User-Defined Functions

You can create your own functions by using the sub directive. User-defined functions have the following syntax:

sub <function_name> {
  #  function statements
  return <value>;
}

Note that Perl does not include function arguments in the function definition as in most other languages. That is because the arguments sent to the function are automatically stored in the $_ variable array. The first argument is stored in $_[0], the second argument is stored in $_[1], and so forth. Within the function, it is the programmer's duty to distill the array into useful variables. For example, to create a function to find the area of a circle, you could use code similar to the following:

sub areaofcircle {
  my $radius = $_[0];
  # area = pi * (r squared)
  my $area = 3.1415 * ($radius ** 2);
  return $area;
}

A popular and efficient way of distilling function parameters is to use code similar to the following:

my(
  $firstparam,
  $secondparam,
  $thirdparam,
  $fourthparam,
) = @_;

This code transfers the contents of the $_ array (referenced in its entirety by @_) to the variables specified. (Of course, you would want to use variable names that are more meaningful to your function.)

It is worth noting that use of the return function is not necessary if the last expression evaluated contains the desired return value (as is the case in the areaofcircle() function example). However, it is usually best to be explicit with your code and always use the return function.

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.