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

Dear Monks

Below I try to add the sub named render to '$my_obj'.
The package (1 file) using Class::Traits looks like:
package Xyz ; use strict ; use warnings ; use Class::Trait 'base' ; package Xyz::XML ; use base qw(Xyz) ; sub render { print "test render XML" ; } package Xyz::YAML ; ...... etc
This is how I try to use it
use Xyz ; Xyz::XML->render() ; # this works Class::Trait->apply($my_obj, 'Xyz::XML') ; # problems
Running this code gives:
test render XML Trait (Xyz::XML) could not be found : Can't locate Xyz/XML.pm ......
It cannot find this file because the package Xyz::XML is inside Xyz.pm.

Any suggestion how to solve this (I would like to have all the 'render' packages in one file) ?

Thnx a lot in advance
LuCa

Update: thnx for the hack and the explanation of the problem!!

Replies are listed 'Best First'.
Re: Class::Traits not happy with multiple packages per file
by ikegami (Patriarch) on Jun 27, 2007 at 14:08 UTC
    Adding the following to Xyz should do the trick.
    $src_pkg = 'Xyz'; $src_pkg =~ s{::}{/}g; $src_pkg .= '.pm'; $dst_pkg = 'Xyz::XML'; $dst_pkg =~ s{::}{/}g; $dst_pkg .= '.pm'; $INC{$dst_pkg} = $INC{$src_pkg};

    It tells Perl that Xyz::XML is already loaded, so Perl will be happy to tell Class::Trait it was successfully loaded when Class::Traits tries to load it.

Re: Class::Traits not happy with multiple packages per file
by stvn (Monsignor) on Jun 27, 2007 at 17:23 UTC

    This has to do with how Class::Trait is loading the Trait, it is trying to load the package with a require hack.

    It is fairly a trivial patch to fix the &_load_trait function in Class::Trait to make it check for the package existence first, and *then* try to require it. You can get the package existince test from Class::Inspector.

    -stvn