For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > October 2004 > Re: Why is not "sub" necessary? What is the difference: block and









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Why is not "sub" necessary? What is the difference: block and
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
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com