Actually, calling a subroutine with an ampersand and no parens does not call
the subroutine with no arguments. (To make it clear, though, I AGREE with
Jos I. Boumans' larger point, just correcting a smaller point that I think
makes his point even more clearly...) Using the ampersand without passing
arguments causes a subroutine to be called with the same arguments as its
calling subroutine. So &foo called from bar('a', 'b') does the same thing as
foo('a', 'b').
Say I've got sub foo, which is supposed to just print out a list of things
passed to it, and print an "empty list" message otherwise:
sub foo {
if (@_) {
print "Output: ", @_, "\n";
}
else {
print "Output: empty list\n";
}
}
Okay, so next I have a subroutine bar(), which calls foo twice:
sub bar {
&foo;
foo();
}
Then, let's say in the main program I call bar() with arguments:
bar('a', 'b');
What will the output be? Well, since you're not explicitly passing anything
to foo() in either case, you'd expect it to be:
Output: empty list
Output: empty list
BUT IT ISN'T. You get:
Output: ab
Output: empty list
I find this a good reason to avoid the & syntax, or to at least always use
parens.
> -----Original Message-----
> From: Jos I. Boumans [mailto:[EMAIL PROTECTED]]
> Sent: Saturday, June 23, 2001 2:33 AM
> To: iansmith; [EMAIL PROTECTED]
> Subject: Re: Re[2]: A better way?
>
>
> Ehm, you cant *just* use & and expect all to stay the same...
> concider the following:
>
> if you use a & you dont need to predeclare a sub if you want to
> leave of the
> parenthesis for an argument list:
> ie:
> &foo #calls sub foo with no arguments
> foo #calls sub foo with no arguments IF you predeclared sub foo
> anywhere... if not, its' a bareword
>
> also, and this is more important, if you set up prototyping for
> your subs, &
> will disable prototype checking...
> now most of the time you dont set up prototypes so it's unlikely you get
> bitten, but the second you change your sub to use prototype's and
> you do not
> leave off the & in your sub calls, they wont get checked
>
> read perldoc perlsub for more information
>
> hope this clears things up,
>
> Jos Boumans
>
> <snip>
>
> > > I am using the most recent from ActiveState, but I tend to stick the &
> > > out there so I can tell at a glance that I am calling a sub. Does it
> > > cause problems or is it just not needed?
> >
> > It doesn't cause any problems that I am aware of. Go ahead and use
> > it if it makes subroutines stick out.
>
>