[Israel.pm] function prototypes

Yitzchak Scott-Thoennes sthoenna at efn.org
Tue Jun 10 22:19:42 PDT 2008


On Tue, June 10, 2008 1:25 pm, Shmuel Fomberg wrote:
> I'm trying to write a function:
> sub MetaField ($&) { ... }
>
> and call it like that: MetaField("data", { $_->ctx->{length} })
> or:
> MetaField("data", $_->ctx->{length})
>
> but only this works: MetaField("data", sub { $_->ctx->{length} })

The "sub" is only optional if the prototype starts with &.  From perlsub:

   An "&" requires an anonymous subroutine, which, if passed as the first
   argument, does not require the "sub" keyword or a subsequent comma.

I'm not sure how perl would know you meant the second example to be
a sub that returns $_->ctx->{length} (based on whatever $_ is set to
if and when MetaField ends up calling the sub), which is what the
third does.

If you somehow meant that $_->ctx->{length} is itself the coderef
you want to pass, there isn't a convenient way to do that, since
"&" explictly expects a new anonymous sub.

I suggest reconsidering using prototypes at all.




More information about the Perl mailing list