0

Possible Duplicate:
When should I use the & to call a Perl subroutine?

I am new to Perl development and just going through sample code.

I came across &LogIt() where I have few basic questions to start with. I got info from Google like it logs error/msgs into the log file.

&LogIt("Failed to create folder."); 

In the above code, what does that '&' represents? Is there any difference/ impact between &LogIt() and LogIt()? Would the msg "Failed to create folder" get printed somewhere? who ll use this msg?

Kindly let me know some basics about &LogIt().

Community
  • 1
  • 1
Perl User
  • 11
  • 5

2 Answers2

3

This is of archeological value. The ampersand was used to call subroutines. You will find all the gory details on that page.

It's still works, but should not be used, except for very special situations (like reference to a subroutine or checking whether it is defined or not).

Note that &foo and &foo() do not mean the same thing. The latter takes the arguments from the parentheses (or none, if none provided). The former cannot be called with arguments, but takes the current value of @_ as arguments. Therefore, the following chunk:

@_ = ( 10, 20 ) ;
&foo( ) ;
&foo ;

sub foo { print "args=$_[0], $_[1]\n" ; }

will produce the following output:

args=, 
args=10, 20
January
  • 16,320
  • 6
  • 52
  • 74
0

The & in front of a function simply behaves like the $ in front of a scalar. It is the sigil for the interpreter to tell what that particular variable is.

However with a function it isn't required if you have parentheses. Thus &foo &foo() and foo() mean almost the same thing.

The difference between them is in the arguments passed to the function. A call to foo() passes no arguments. A call to &foo passes in the current @_ to foo.

The advantage of being explicit and using the sigil is you can omit the empty () when you use it. eg

&foo
foo()

If foo doesn't check its arguments or if the current @_ is empty.

Or if you have to call foo(@_) you can simply write

`&foo`

However I would say that many perl programmers still tend to use the () even in situations when it isn't required as the only other language (that I know of) that has optional parentheses is COBOL.

Simply decide whether you intend to use the & throughout the codebase and stick to it!! Otherwise it is can be confusing (or annoying) to read.

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134