"Functional programming is a style of programming that emphasizes the evaluation of expressions rather than the execution of commands."
I've came to think, what reminds of this style in Perl. Here are some examples that immediately popped up in my head:
Mapping
@arr = (1, 2, 3, 4, 5); map {print "** $_ **\n";} @arr;
Anonymous subs & treating subs as data
$ast_print = sub {print "** $_[0] **\n"}; process_and_print(25, $ast_print); sub process_and_print { my $val = $_[0]; my $print_func= $_[1]; #..... processing .... &$print_func($val); }
Eval: evaluating strings as Perl expressions
$op = "print \"hello\""; eval $op;
The latter reminds me of a nice example the Lisp people like to show. How do you write a Lisp interpreter ? Easy:
(loop (print (eval (read))))
You can do the same in Perl, and it isn't less easy (though a bit more obfuscated - the Perl way :)
while (<>) { eval; print $@; }
Note: all of the above are toy examples, chosen to demonstrate their specific purposes.
And I wanted to consult you, knowledgeable monks, what other examples do you have in mind ? Some very cool things may be done with the constructs shown above. eval is frequently used in obfuscations, but it is a very powerful tool - for code reading and executing code, etc.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Functional programming with Perl
by adrianh (Chancellor) on Dec 01, 2002 at 14:09 UTC | |
|
Re: Functional programming with Perl
by gjb (Vicar) on Dec 01, 2002 at 15:57 UTC | |
|
Re: Functional programming with Perl
by hawtin (Prior) on Dec 01, 2002 at 21:41 UTC | |
by spurperl (Priest) on Dec 02, 2002 at 07:49 UTC | |
by Dominus (Parson) on Dec 02, 2002 at 15:42 UTC | |
by gjb (Vicar) on Dec 02, 2002 at 09:00 UTC | |
by hding (Chaplain) on Dec 02, 2002 at 13:16 UTC |