Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call Perl subroutines with no arguments as marine() or marine?

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?

like image 418
Nano HE Avatar asked Jan 13 '10 13:01

Nano HE


People also ask

How do you call and identify a subroutine in Perl?

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.

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.

What is used to identify the subroutine in Perl?

The first thing you need to do is create a subroutine. sub keyword is used to define a subroutine in Perl program.


2 Answers

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.

like image 197
brian d foy Avatar answered Oct 13 '22 00:10

brian d foy


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:
like image 26
mob Avatar answered Oct 13 '22 00:10

mob