Perl6 Object Oriented Cookbook (v0.2.1)  
Section 1: Introduction to Object Oriented Perl6  
 
Recipe 1.9: Using Subroutines as Objects
Last Updated: Sep 8, 2003
Status: Very Likely
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
4.60 Rating, 5 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
2.40 Rating, 5 Votes  

Problem:  

You want to use a subroutine as if it were an object.

Solution:  

Make sure you use the '&' sigil:

sub mysub { ... };

my $var1 = &mysub.foo;  # call foo method on the object '&mysub'
my $var2 = mysub.foo;   # same as mysub().foo()

Discussion:

Typically, including a subroutine name in a statement calls that subroutine, returning a value: simply saying

my $var2 = mysub.foo;
therefore calls mysub first, then calls the foo method on whatever value mysub returned. Most of the time this is what you want.

If you want to perform a method call on the subroutine object itself, and not on the value the subroutine will return, you need to specify the full name of the subroutine, including the initial '&' character.

my $var1 = &mysub.foo;

See later recipes for the methods available on a subroutine.


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page