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

Paul Fenwick pjf at perltraining.com.au
Sun Oct 5 21:24:37 CDT 2003


G'day Everyone,

On Mon, Oct 06, 2003 at 12:13:12PM +1000, Jacinta Richardson wrote:

> 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;

Actually, it's worth mentioning what the magic stuff is here, since it
can be a great big gotcha that you may not expect.

Calling &foo without parentheses or arguments passes in the current
value of @_ (the caller's argument list) to the subroutine.  This
is not something that every Perl programmer is aware, and certainly
not something which is obvious from looking at the code.  Most
people assume that &foo calls the subroutine with no arguments.

For this reason, I can highly recommend avoiding the use of & except
when absolutely needed (such as when taking a subroutine ref).  If
you need to make something a subroutine call when it would otherwise
be interpreted as a bareword:

	$hash{foo};		# Foo is considered a (bareword) string.

then parentehses are highly preferred:

	$hash{foo()};		# Use the result of foo().

	VS

	$hash{&foo};		# Unexpectedly use the result of foo(@_).

Cheers,

	Paul

-- 
Paul Fenwick <pjf at perltraining.com.au> | http://perltraining.com.au/
Director of Training                   | Ph:  +61 3 9354 6001
Perl Training Australia                | Fax: +61 3 9354 2681



More information about the Melbourne-pm mailing list