Hello Monks,
everyone knows the basic principles of closures:
#!/usr/bin/perl -w
use strict;
sub compare {
my @mem;
return sub {
my $x = shift;
my $y = shift;
push @mem,$y if($x eq $y);
return @mem;
};
};
my $code = &compare;
print "IT1: ",&$code('a','b'),"\n";
print "IT2: ",&$code('b','b'),"\n";
print "IT3: ",&$code('a','c'),"\n";
print "IT4: ",&$code('c','c'),"\n";
Unfortunatedly this behaviour doesn't suit the needs I actually encounter. Much more suitable would be a subroutine, that is able to remember its state whenever
called. Without the additional
referencing
my $code = &compare; stuff.
I.e. AS IF it used a global variable. But it isn't allowed
to use global variables. Just whenever you call such
a self-aware metaclosure it returns something back that
can depend on the last state it had.
I tried to implement that with a closure inside a sub, but
failed miserably. Anyone who could help me out here?
Thank you and
Bye
PetaMem
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.