On Wed, Jul 7, 2010 at 02:19, Srinivasa Chaitanya T <tschaitanya....@gmail.com> wrote: > Hi, > How can I write functions which accept block as an argument? Basically I > want to create a function with like which just executes the block and > doesn't create an array. > > -- > T Srinivasa Chaitanya >
Unfortunately, in Perl 5 you cannot create a function exactly like map without resorting to XS trickery; however, you can easily create a function that takes a function as an argument. All you have to do is pass a code reference, or coderef for short, to the function. You can create coderefs in two ways. If you want to create a reference to an already existing function you say my $coderef = \&functionname; If you just want to pass some arbitrary code to a function for it to run later, a full blown named function is overkill. That is why we have anonymous subroutines in Perl: my $coderef = sub { print "hello\n" }; The anonymous sub routine above returns a coderef, but does not execute the statements between the curly braces. You can call a coderef by saying $coderef->("argument1", "arguement2", "etc"); This is the same for coderefs that come from named or anonymous sources. Bellow I have created a [reduce][1] function in pure Perl code. You should not use this function as there is a much better XS based one in [List::Util][2]. You may want to Mark Jason Dominus's book [Higher Order Perl][3] which is happily also available [on the web][4]. #!/usr/bin/perl use strict; use warnings; sub reduce { #handle no args or only the function arg return if @_ < 2; #handle only the function arg and one data arg return $_[1] if @_ == 2; my ($user_defined_function, $first, $second) = @_; my $accumulator = $user_defined_function->($first, $second); for my $next (@_[3 .. $#_]) { $accumulator = $user_defined_function->($accumulator, $next); } return $accumulator; } sub sum { return reduce sub { shift() + shift() }, @_; } print sum(1, 2, 3, 4), "\n"; [1]: http://en.wikipedia.org/wiki/Reduce_(higher-order_function) [2]: http://perldoc.perl.org/List/Util.html [3]: http://www.powells.com/biblio?PID=29575&cgi=product&isbn=1558607013 [4]: http://hop.perl.plover.com/ -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/