Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Answer: How do I reference methods?

( #62749=categorized answer: print w/ replies, xml ) Need Help??

Q&A > object-oriented programming > How do I reference methods? contributed by mirod

You can use closures:

#!/bin/perl -w use strict; # just a simple package package obj; sub new { return bless {content => $_[0]}; } sub print { my $self= shift; print ref($self), ": ", $self->{content}, " - ", @_, "\n"; } # now the main stuff package main; my $p; # that's your method reference { my $o= obj::new( "toto"); # the normal way: create $o->print( "tata"); # print $p=sub { $o->print(@_); }; # create the closure (an anon sub) $p->( "titi"); # use it to print $o= obj::new "foo"; # change the object $p->("tutu"); # print using the new object } my $o= obj::new "bar"; # the $o used with the closure is not # in scope any more $p->("tutu"); # but $p still uses it

This returns:

obj: toto - tata obj: toto - titi obj: foo - tutu obj: foo - tutu

Note that as far as convenience goes calling $o->print or $p->print is pretty similar ;--)

Comment on Answer: How do I reference methods?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (10)
As of 2015-07-29 02:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls