Object::Lexical.3pm

Langue: en

Version: 2003-07-20 (mandriva - 01/05/08)

Section: 3 (Bibliothèques de fonctions)

NAME

Object::Lexical - Syntactic Sugar for Easy Object Instance Data & More

SYNOPSIS

   use Object::Lexical;
   use Sub::Lexical;
 
 
   sub new {
 
 
     my $counter;
     our $this;
 
 
     my sub inc { 
        $counter++; 
     }
 
 
     my sub dec { 
        $counter--;
     }
 
 
     my sub inc3x {
       $this->inc() for(1..3); 
     }
 
 
     instance();
 
 
   }
 
 

ABSTRACT

Object::Lexical provides syntactic sugar to create objects.

Normal "my" variables are used for instance data. $this is automatically read off of the argument stack. This follows ``real'' OO languages, where user code need not concern itself with helping the language implement objects.

Normal OO Perl code is ugly, hard to read, tedious to type, and error prone. The "$self-"{field}> syntax is cumbersome, and using an object field with a built in, like "push()", requires syntax beyond novice Perl programmers: "push @{$self-"{field}}, $value>. Spelling field names wrong results in hard to find bugs: the hash autovivicates, and no ``variables must be declared'' warning is issued.

DESCRIPTION

"instance()" returns a new object that subclasses the current object, and contains all of the just-defined methods. The object returned is a blessed symbol table (stash) reference, which functions like a blessed hash reference for most purposes. In other words, it is a normal object.

"instance()" takes an optional argument: the name of the package the object being created is to belong to. If the "new()" method reads the class name off of the argument stack, this class name should be passed to "instance()", to support the creation of subclasses of your class. This is similar to the operation of "bless()", except "instance()" will read the class name off of the stack for you if you don't.

The "use Method::Lexical" line takes optional arguments: ``nononlex'' specifies that non-lexically defined methods shouldn't be moved. Methods defined using "*name = sub { }" and "sub name { }" won't be moved. If subroutines are created out side of the "sub new { }" block, then this option should be specified, or else the subroutines will mysteriously disappear. ``noexport'' specifies that "method()" and "instance()" should not be exported into your namespace. To get at these functions, you will need to qualify their names: "Object::Lexical::method()" and "Object::Lexical::instance()", respectively. ``nowrap'' specifies that methods should be wrapped in logic that reads $this automatically, as they are moved into their new symbol table. If you want to refer to $this as $_[0], or you want to process it yourself, or you want keep memory usage on par with normal objects, use this.

"instance()" is the heart of this module: lexically scoped methods (coderefs held in "my" variables) and methods placed into the symbol table are moved into a new namespace created just for that object instance. A thin wrapper is placed around each symbol table entry in this namespace that reads the reference to the current object into an "our" variable named $this.

Any number of independent objects can be returned by "new()". By defining methods in side the block of the "new()" method, each returned object has its own private copies of each "my" variable. This uses the ``lambda closure'' feature of Perl. A closure is code that holds references to variables - in this example, $counter will go out of scope, but "inc", "dec", "inc3x" all keep a reference to it. The next time "new()" is run, a new $counter lexical will be created, and new methods will be created that reference that.

This serves to avoid the messy "$this-"{counter}++> syntax, making it easier to refactor code, move code into methods from subroutines, and turn plain old modules into objects.

ALTERNATE IDIOMS

The ``lite'' approach: use built in Perl constructs to create normal closures. They may either be placed into the symbol table or stored in "my" variables. These three alternate idioms remove the need to "use Sub::Lexical". Sub::Lexical uses souce filtering, which may clash with other source filters or introduce bugs into code.

   package MyPackage;
 
 
   use Object::Lexical;
 
 
   sub new {
 
 
     my $counter;
     our $this;
 
 
     *inc = sub { $counter++ };
 
 
     *dec = sub { $counter-- };
 
 
     *inc3x = sub {
       $this->inc() for(1..3); 
     };
 
 
     instance();
 
 
   }
 
 

Rather than use globals, lexicals may be used:

   package MyPackage;
 
 
   use Object::Lexical;
 
 
   sub new {
 
 
     my $counter;
     our $this;
 
 
     my $inc = sub { $counter++ };
 
 
     my $dec = sub { $counter-- };
 
 
     my $inc3x = sub {
       $this->inc() for(1..3); 
     };
 
 
     instance();
 
 
   }
 
 

A "method()" function is provided:

   use Object::Lexical;
   no strict 'subs';
 
 
   sub new {
 
 
     my $counter;
     our $this;
 
 
     method { $counter++ } inc;
 
 
     method { $counter-- } dec;
 
 
     method { 
       $this->inc() for(1..3); 
     } inc3x;
 
 
     instance();
 
 
   }
 
 

This is logically the same thing as the previous example, using "my" with closures.

BUGS

Making a function call instead of a method call, treating the blessed stash (symbol table) as a hash and looking up the method in it, and invoking it directly after making a normal method call to that method causes a coredump in Perl 5.8.0, 5.6.1, and perhaps earlier. Voodoo. This was meant to be supported as a feature, to allow hash style access to objects that are only namespaces full of closures.

   $ob->{method}->();
 
 

Subs declared outside of the "new()" block are annihilated in this version. Specifically, they are moved into the first object created, never replunished, as they aren't created run-time from inside the "new()" block. Use the 'nononlex' option to "use" to avoid this. You'll need to use one of the three lexical subs idioms: Sub::Lexical, the "method" statement, or "my $subname = sub { }", the plain old Perl closure syntax.

Perl prototypes support magic that allows allows user defined functions follow the form of builtings "grep { } @list" and "map { } @list" to be created, but not of the form used by the builtin "sub name { }". This gives "method { }" a strange syntax.

Magic may not play nice with out modules that mangle the nametable or other trickery. Best to confine use to small container objects and the like for now. Unless you're brave.

EXPORT

"instance()" is always exported, and so is "method()" - unless the 'noexport' option is given.

SEE ALSO

http://perldesignpatterns.com/?AnonymousSubroutineObjects
Class::Classless
Can easily provide the same facility as this module if closures are passed to the "sub()" method. Requires more syntax - Object::Lexical is specialized.
Class::Object
Ditto. Barrowed code from.
ImplicitThis
ImplicitThis, an earlier attempt, wrapped methods to automatically read $this, but it was error prone, and ignored the problem of accessing instance data.
Sub::Lexical
Provides a syntax for lexically scoped subroutines.

AUTHOR

Scott Walters, <scott@slowass.net> Copyright 2003 by Scott Walters

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.