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"? Apparently he is passing a function by reference. Is this a
block or an expression? The camel book says map takes a block or an
expression and I don't understand the difference.

Also, can someone elaborate on his use of prototyping here when he defines
function iterate? I don't understand the "&@". 

And, what about the use of the keyword "for". Should that not be "foreach"?
The code works so I guess it is correct.


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);

Here is what I get:
cd c:/OpenPerlIDE_1.0.11.409/
perl test_expression.pl
Not a CODE reference at test_expression.pl line 5.

Hello 

 begin function iterate


Compilation exited abnormally with code 255 at Fri Oct 29 10:27:02

I tried removing the comma from the call to iterate, but that did not help.

  Thanks,
     Siegfried


> On Sun, 10 Oct 2004 14:30:32 -0600, Siegfried Heintze
<[EMAIL PROTECTED]> wrote:
> > 
> > The map and the sort statements are strange. Why don't they require a 
> > comma between the first and second arguments?
> 
> They are not special, they are just using a special semantic built into
perl.
> 
> Consider the following:
>
----------------------------------------------------------------------------
------------
> sub iterate(&@)
> {
>       my $code = shift;
>       &$code for @_;
> }
> 
> @data = ( "jack", "jill", "jenny" );
> 
> iterate { print "Hello $_\n" } @data
>
----------------------------------------------------------------------------
------------
> 
> The "iterate" function takes a CODE reference and an ARRAY of stuff (same
as MAP and GREP and SORT).  It will then blindly iterate over the array of
stuff and invoke the code for each element.
> 
> The basic rule is, a BLOCK OF CODE does not require a comma after it,
because it is self-enclosing (ie, it has braces). 
> 
> Consider then, that since 'map {xx} @data' is actually parsing {xx} as a
code reference, the same way 'my $prog = { some code}' does, you can also do
> 
> sub sortfilter($$){
>     stuff
> }
> 
> sort \&sortfilter, @data
> 
> or even
> 
> sub special_sort(&@)
> {
>      my $sort_func = shift;
>      sort  $sort_func, @_
> }
> 
> You should probably read more on anonymous subroutines and code blocks.
(and even closures).
> 
> Cheers.
> David
> 
> > 
> > Thanks,
> >    Siegfried


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to