Re^2: What's so bad about &function(...)?
by japhy (Canon) on Dec 07, 2005 at 18:17 UTC
|
What is the mysterious side effect of using a leading ampersand? The only side effect I can think of, off the top of my head, is that it avoids prototypes, and prototypes, I would expect, are outside the realm of "simple code".
| [reply] |
|
|
Yes, but not everyone programs in a vacuum. Sooner or later they'll start using code which does have prototypes. Imagine, for example, that they start using Test::More. Those functions all have prototypes and using the leading ampersand is sure to bring them woe. Imagine, for example, typing "is" instead of "ok":
&is(some_func(3,4));
The prototype is now disabled so they don't get the compile-time failure telling them that the test function has been called incorrectly. If you're new to testing or that's buried in bunch of other tests, it can be quite difficult to figure out.
| [reply] [d/l] |
|
|
Sooner or later they'll start using code which does have prototypes.
Not if I can help it. Unless it's a specialized function that is trying to imitate a built-in, prototypes are forbidden in the code that I control.
| [reply] |
|
|
| [reply] [d/l] |
|
|
|
|
|
|
OTOH, if they write something like:
$a[0] = some_func(2, 3);
$a[1] = 17; # Expected outcome.
&is(@a);
their code runs fine, and it isn't getting generating errors about a mismatch of the number of arguments. I'd say that '&' disables mysterious side-effects.
| [reply] [d/l] |
|
|
If you don't specify arguments, it passes any existing @_.
#!/usr/bin/perl
use strict;
use warnings;
yes_ampersand("yes\n");
no_ampersand("no\n");
sub foo {
print $_[0];
}
sub yes_ampersand {
print $_[0];
&foo;
}
sub no_ampersand {
print $_[0];
foo;
}
Here's the output:
yes
yes
no
Use of uninitialized value in print at ampersands.plx line 9.
| [reply] [d/l] [select] |
|
|
I made it clear in my original node that I'm not referring to a bare &foo, but rather &foo(...).
| [reply] [d/l] [select] |
|
|
|
|