Declaring and Invoking Functions
Learn how to declare and invoke a function in Perl.
We'll cover the following
A function (or subroutine) in Perl is a discrete, encapsulated behavior unit. A program is a collection of little black boxes where the interaction of these functions governs the program’s control flow. A function may have a name. It may consume incoming information. It may produce outgoing information.
Functions are a prime mechanism for organizing code into similar groups, identifying individual pieces by name, and providing reusable units of behavior.
Declaring functions
We use the sub
built-in to declare a function:
sub greet_me { ... }
Now, we can invoke greet_me()
from anywhere within our program.
Just as we may declare a lexical variable but leave its value undefined, we may declare a function without defining it. A forward declaration tells Perl to record that a named function exists. We may define it later:
sub greet_sun;
Invoking functions
We use postfix parentheses to invoke a named function. Any arguments to the function may go within the parentheses. While these parentheses are not strictly necessary for these examples, even with strict
enabled, they provide clarity to human readers and Perl’s parser. When in doubt, use them.
Get hands-on with 1400+ tech skills courses.