|
Wed Sep 19 18:09:38 EDT 2007
fun with manufactoring functions in Perl
--
This is my first forray into manufacturing functions ever - not
just using Perl. Perl just makes it easy. To make things overly
complicated, the ret_sub function returns the function that does
the actual creation - one more function than is needed, but it
helped illustrate to me how things were working.
The following code generates an anonymous function given the ar-
gument. The resulting references are stored in an array, and are
then called one after another starting at line 19.
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4
5 sub ret_sub {
6 return sub { my $num = shift;
7 return sub { print "hello $num"; };
8 };
9 }
10
11 my $sub = ret_sub(); # get the real factory
12 my @funcs = ();
13
14 for (1..10) {
15 my $x = $sub->($_);# make that function
16 push(@funcs,$x); # store in array
17 }
18
19 foreach (@funcs) {
20 $_->(); # execute the current sub ref
21 }
22
23 1;
--
Powered by vee Copyright © 2006-2008
|
|