As per my sample code below, there are two styles to call a subroutine: subname
and subname()
.
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
use 5.010;
&marine(); # style 1
&marine; # style 2
sub marine {
state $n = 0; # private, persistent variable $n
$n += 1;
print "Hello, sailor number $n!\n";
}
Which one, &marine();
or &marine;
, is the better choice if there are no arguments in the call?
Define and Call a Subroutine&subroutine_name( list of arguments ); Let's have a look into the following example, which defines a simple function and then call it. Because Perl compiles your program before executing it, it doesn't matter where you declare your subroutine.
You can pass various arguments to a Perl subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in [0],thesecondisin_[1], and so on.
The first thing you need to do is create a subroutine. sub keyword is used to define a subroutine in Perl program.
In Learning Perl, where this example comes from, we're at the very beginning of showing you subroutines. We only tell you to use the &
so that you, as the beginning Perler, don't run into a problem where you define a subroutine with the same name as a Perl built-in then wonder why it doesn't work. The &
in front always calls your defined subroutine. Beginning students often create their own subroutine log
to print a message because they are used to doing that in other technologies they use. In Perl, that's the math function builtin.
After you get used to using Perl and you know about the Perl built-ins (scan through perlfunc), drop the &
. There's some special magic with &
that you hardly ever need:
marine();
You can leave off the ()
if you've pre-declared the subroutine, but I normally leave the ()
there even for an empty argument list. It's a bit more robust since you're giving Perl the hint that the marine
is a subroutine name. To me, I recognize that more quickly as a subroutine.
The side effect of using &
without parentheses is that the subroutine is invoked with @_
. This program
sub g {
print "g: @_\n";
}
sub f {
&g(); # g()
&g; # g(@_)
g(); # g()
g; # g()
}
f(1,2,3);
produces this output:
g: g: 1 2 3 g: g:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With