What is exactly the difference (if there is any) between:
sub foobar() {
# doing some stuff
}
and
sub foobar {
# doing some stuff
}
I see some of each, and the first syntax sometimes fail to compile.
The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier.
Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.
You can return a value from Perl subroutine as you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.
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.
By putting the ()
on the end of the subroutine name, you are giving it a prototype. A prototype gives Perl hints about the number and types of the arguments that you will be passing to the subroutine. See this section in perlsub for details.
Specifically, ()
is the empty prototype which tells Perl that this subroutine takes no arguments and Perl will throw a compilation error if you then call this subroutine with arguments. Here's an example:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
sub foo {
say 'In foo';
}
sub bar() {
say 'In bar';
}
foo();
bar();
foo(1);
bar(1);
The output from this is:
Too many arguments for main::bar at ./foobar line 18, near "1)"
Execution of ./foobar aborted due to compilation errors.
It's that last call to bar()
(the one with the argument of 1) which causes this error.
It's worth noting that Perl's implementation of prototypes is generally not as useful as people often think that they are and that outside of a few specialised cases, most Perl experts will avoid them. I recommend that you do the same. As of Perl v5.22, the experimental "signatures" feature is in testing that will hopefully accomplish many of the goals programmers from other languages would have expected from prototypes.
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