Useless use of a (constant|hash element) in void context?

Jacinta Richardson jarich at
Sun Oct 5 21:13:12 CDT 2003

On Mon, 6 Oct 2003, ADFH wrote:

> > If you prefix something with an ampersand you're saying that it's a
> > subroutine:
> > 	&some_sub();
> Ok, so when I call a function foo like:
> 	print foo;
> I'm implying:
> 	print &foo();
> ... assuming there are no variables called foo in the current
> context/scope?

Well... there are some (arcane, archaic and only-good-for-obfu)
differences between calling subroutines with the ampersand and
not, but leaving those aside... 

When you call a function foo like:
	print foo;
you run the risk of confusing Perl with regards to what it should expect
foo to be.  If your subroutine definition of foo is below your call, and
you're using strict (because of course you are) then your code probably
won't compile.

When you call a function foo like:
	print foo();		# this is the preferred way
then this is equivalent to calling it as:
	print &foo();
and is also equivalent (mostly, ignoring the magic stuff) to:
	print &foo;

You will need to preceed your subroutine calls with ampersands if you've
named one of your subroutines the same name as a built in Perl function.
But don't do that:

	print "foo";	# Uses built in Perl function print
	&print("foo");	# Uses my subroutine print
	&print "foo";	# Uses my subroutine print

The need for using ampersands in many cases went out with Perl 4.  Which
is good.  There are a few cases where they remain important (such as
taking references to subroutines) but typically good Perl code (according
to my opinions) doesn't tend to use them.  I prefer:
	print foo();
over any of the alternatives.

All the best,


   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +613 9354 6001         |  
  _..`--'_..-_/  /--'_.' ,'           | contact at |
(il),-''  (li),'  ((!.-'              |   |

More information about the Melbourne-pm mailing list