why doesn't this argument list need a comma after the 1st argument?

D

Dave Slayton

Sorry, another newbie question:

I'm reading this very interesting book on Perl (Effective Perl Programming
by Joseph N. Hall with Randal L. Schwartz), and here on page 110 there's an
example of a
call to a (prototyped) subroutine that requires 3 arguments: a coderef, a
scalar, and an array, and here's the call:

for_n {print "$_[0], $_[1]\n"} 2, @a;

I understand the parentheses around the list of arguments are optional, and
that the anonymous subroutine does not require the "sub" keyword, but what I
don't understand is how the call gets away with not having a comma after the
closing curly brace and before the 2. Can anyone shed some light on this
for me?
 
B

Ben Morrow

Quoth "Dave Slayton said:
Sorry, another newbie question:

I'm reading this very interesting book on Perl (Effective Perl Programming
by Joseph N. Hall with Randal L. Schwartz), and here on page 110 there's an
example of a
call to a (prototyped) subroutine that requires 3 arguments: a coderef, a
scalar, and an array, and here's the call:

for_n {print "$_[0], $_[1]\n"} 2, @a;

I understand the parentheses around the list of arguments are optional, and
that the anonymous subroutine does not require the "sub" keyword, but what I
don't understand is how the call gets away with not having a comma after the
closing curly brace and before the 2. Can anyone shed some light on this
for me?

It's a special case. Prototypes were introduced to allow you to write
subs that parse like Perl builtins; so, to allow a map-like sub to be
written, a sub with its first argument prototyped '&' will accept a bare
block (without a comma) like this, and treat it as an anon sub.

Actually, this is the only case where the sub keyword is optional: a sub
prototyped as ($&$) would still need to be called like

foo 1, sub {...}, 2;

See perldoc perlsub for all the details.

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top