Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== In Perl == In [[Perl]], a function object can be created either from a class's constructor returning a function closed over the object's instance data, blessed into the class: <syntaxhighlight lang="perl"> package Acc1; sub new { my $class = shift; my $arg = shift; my $obj = sub { my $num = shift; $arg += $num; }; bless $obj, $class; } 1; </syntaxhighlight> or by overloading the <code>&{}</code> operator so that the object can be used as a function: <syntaxhighlight lang="perl"> package Acc2; use overload '&{}' => sub { my $self = shift; sub { my $num = shift; $self->{arg} += $num; } }; sub new { my $class = shift; my $arg = shift; my $obj = { arg => $arg }; bless $obj, $class; } 1; </syntaxhighlight> In both cases the function object can be used either using the dereferencing arrow syntax ''$ref->(@arguments)'': <syntaxhighlight lang="perl"> use Acc1; my $a = Acc1->new(42); print $a->(10), "\n"; # prints 52 print $a->(8), "\n"; # prints 60 </syntaxhighlight> or using the coderef dereferencing syntax ''&$ref(@arguments)'': <syntaxhighlight lang="perl"> use Acc2; my $a = Acc2->new(12); print &$a(10), "\n"; # prints 22 print &$a(8), "\n"; # prints 30 </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)