Code Comments

Programming Forum and web based access to our favorite programming groups.
For Programmers: Free Programming Magazines | New: Database administration forum
Registration is free! Edit your profileCalendarFind other membersFrequently Asked QuestionsSearch -> 
Post New Thread











Thread
Author

Re: Why is not "sub" necessary? What is the difference: block and
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"?[/color
]

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

Report this thread to moderator Post Follow-up to this message
Old Post
Gunnar Hjalmarsson
10-29-04 08:56 PM


Sponsored Links




Last Thread Next Thread Next
Search this forum -> 
Post New Thread

PERL Beginners archive

Show a Printable Version Send to friend Email This Page to Someone! subscribe to this thread Receive updates to this thread
Computer Consultants
Programming Jobs
Visual Basic Controls
SQL Server Programming
Webservices
Java Security
Visual Studio
C# Programming
Visual J++
Software engineering
Open source Software
Perl Programming
PHP Programming
ASP Programming
ASP .NET Programming
Visual Basic Programming
Windows Scripting Host
Java Programming
Java Help
Java Beans
VBScript
Cobol
MAC Applications
Unix Programming
Forum Jump:
All times are GMT. The time now is 05:16 AM.

 
Free MCSE Braindumps | Real Estate Topics

Programming forum archive

Copyrights CodeComments.com 2004 - 2006

Powered by vBulletin Copyright 2000-2006 Jelsoft Enterprises Limited.