Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

How to implement closures in Package

by perlCrazy (Monk)
on Mar 13, 2007 at 10:53 UTC ( [id://604501]=perlquestion: print w/replies, xml ) Need Help??

perlCrazy has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,
I want to write one method inside one package that returns subroutine reference.
Then from calling program I want to call that method. Below is my code :
package myTest; use strict; use vars qw($VERSION %EMP @ARR $VAL); $VERSION = '0.01'; %EMP = ("1", "Ravish", "2", "Mike"); @ARR = (5,6,7,8); sub new { my $package = shift; return bless({}, $package); } sub add { my $self = shift; my ($a, $b) = @_; my $c = $a + $b; push @ARR, $c; return @ARR; } sub greet { my($grt) = @_; return sub { my($subject)= @_; print "$grt $subject \n"; }; } 1; this is my calling program : use strict; use myTest; my @chk = @myTest::ARR; my $obj = myTest->new(); my $rs1 = $obj->greet("hello"); my $rs2 = $obj->greet("my fair"); &$rs1("world") ; # it should print "hello world" but not &$rs2("lady") ; # it should "my fair lady" but not
Is this the right way to call that function from subroutine ? Any help will be appriciated.
Thanks in advance

Replies are listed 'Best First'.
Re: How to implement closures in Package
by tfrayner (Curate) on Mar 13, 2007 at 11:03 UTC
    Hi,

    You're just missing the assignment to $self in greet():

    sub greet { my($self, $grt) = @_; return sub { my($subject)= @_; print "$grt $subject \n"; }; }
    This should then work as you expect.

    Cheers,

    Tim

Re: How to implement closures in Package
by davorg (Chancellor) on Mar 13, 2007 at 11:04 UTC
      Thanks a lot :) It is working now

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://604501]
Approved by tfrayner
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2024-03-28 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found