in reply to Re: Is it ok to mix functional and oo programming in one package?
in thread Is it ok to mix functional and oo programming in one package?

Here's a first pass at what I was talking about above:

use strict; use warnings; package ImpWrap; sub import { my $this = shift; my $class = shift; my $method = shift; my $caller = (caller)[0]; warn "Importing $class/$method from $caller\n"; my $obj = $class->$method(@_); { no strict 'refs'; my $autoload = sub { our $AUTOLOAD; my ($al_method) = $AUTOLOAD =~ /::([^:]*)$/g; if ( $class->can( $al_method ) ) { *{ $AUTOLOAD } = sub { $obj->$al_method( @_ ); }; goto &{$AUTOLOAD}; } else { require Carp; Carp::croak "Undefined subroutine $AUTOLOAD"; } }; # Insert AUTOLOAD function; warn "Setting autoload\n"; *{ "$caller\::AUTOLOAD" } = $autoload; } } package Fuz; use Data::Dumper; sub bizzle { my $self = shift; print "bizzle: $self\n"; print Dumper $self; } sub new { my $class = shift; bless {@_}, $class; } package Foo; our @ISA = ('Fuz'); package IW::Foo; import ImpWrap 'Foo', 'new', (1..4); package IW::Fuz; import ImpWrap 'Fuz', 'new', (11..20); package main; IW::Foo::bizzle(); IW::Fuz::bizzle(); IW::Foo::Grazzle();

I'm sure there are lots of things this doesn't do quite right yet. I know it doesn't handle autoloads in the wrapped object class properly. Or inherited autoloads.

The main thing is that it seems to work for basic usage. I create an AUTOLOAD function for the wrapper package that is a closure around the wrapped object. As a result, any class methods will be called as instance methods. I could make it possible to define a list of class methods to call by name, methods to skip, and so forth, by adding appropriate argument handling to the import subroutine.

Anyhow, this is just a start. I'd like to get proper handling of AUTOLOADs in wrapped objects (with inheritance) and any other gotchas I can think of handled. Any suggestions are welcome.


TGI says moo

  • Comment on Re^2: Is it ok to mix functional and oo programming in one package?
  • Download Code