| Gunnar Hjalmarsson 2004-10-29, 3:56 pm |
| Siegfried Heintze wrote:
> I'm trying to understand the map function in perl and have been studying
> David's response to my earlier query.
>
> When David calls his iterate function, why does he not need to use the
> keyword "sub"?
Because he used prototypes instead.
> Also, can someone elaborate on his use of prototyping here when he defines
> function iterate? I don't understand the "&@".
They make the function expect a coderef followed by a list.
> And, what about the use of the keyword "for". Should that not be "foreach"?
Those are synonymous (at least as keywords...).
> Lastly, I tried to rewrite the code so I could understand it. Why does not
> this work?
>
> sub iterate{
> my $code = shift;
> print " begin function iterate\n";
> foreach $x (@_) { &$code($x) ; }
> print " end function iterate\n";
> }
> iterate ({ print "Hello $_\n" }, @data);
This is one way to make it "work":
sub iterate {
my $code = shift;
print " begin function iterate\n";
foreach my $x (@_) { &$code($x) ; }
print " end function iterate\n";
}
iterate ( sub { print "Hello $_[0]\n" }, @data);
--------------^^^----------------^^^^^
'sub' makes the block a coderef, and since you are setting $x in your
foreach loop, $_ is not set.
An alternative:
sub iterate(&@) {
my $code = shift;
print " begin function iterate\n";
foreach my $x (@_) { &$code($x) ; }
print " end function iterate\n";
}
iterate { print "Hello $_[0]\n" } @data;
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
|