"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.
In reply to Functional programming with Perl by spurperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |