Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a Perl sub declaration with and without parentheses?

Tags:

perl

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.

like image 853
Nati Avatar asked Jul 13 '15 06:07

Nati


People also ask

What is sub in Perl script?

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.

What does @_ mean in Perl?

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.

How do I return a value from a subroutine in Perl?

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.

How do you pass arguments in Perl 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.


1 Answers

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.

like image 75
Dave Cross Avatar answered Oct 18 '22 15:10

Dave Cross