Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Runtime instantiation decisions

by Kanji (Parson)
on Mar 30, 2002 at 17:02 UTC ( #155443=note: print w/replies, xml ) Need Help??

in reply to Runtime instantiation decisions

As it happens, merlyn posted something similar the other day, which you could adapt easily (untested)...

# in Astro::Observation sub new { my $self = shift; # Foo->new('bar',@_) => Foo::Bar->new(@_) my $class = __PACKAGE__ . "::" . ucfirst(shift); require autouse; autouse->import( $class, "$class\::new" ); return $class->new( @_ ); }


... or not.

After trying out the above, I kept getting the error "autouse into different package attempted", which appears to be a known bug in autouse when using a module that isn't at the root of it's namespace (ie, Foo would work, but Foo::Bar doesn't).

Perhaps merlyn has a patched version of autouse?

Anyhoo, another way to do it (and as jeffa suggests) is with eval...

sub new { my $self = shift; # Foo->new('bar',@_) => Foo::Bar->new(@_) my $class = __PACKAGE__ . "::" . ucfirst(shift); eval "require $class;"; # Note: "" *NOT* {} ! if ( $@ ) { # whoops, there was an error warn( $@ ); # require'ing $class; perhaps return; # it doesn't exist? } return $class->new( @_ ); }


Replies are listed 'Best First'.
•Re: Re: Runtime instantiation decisions
by merlyn (Sage) on Mar 30, 2002 at 18:29 UTC
    This is expensive and dangerous:
    eval "require $class;"; # Note: "" *NOT* {} !
    whereas this is cheaper and safer (no firing up of the compiler):
    (my $file = $class) =~ s#/#::#g; require $file;
    Please note that for future programs. (Yes, portabilty to macs and VMS is sacrificed.. for that, pull down File::Spec. But this works on Unix and Windows.)

    -- Randal L. Schwartz, Perl hacker

      Don't you mean something like this instead?
      (my $file = $class) =~ s^::^/^g; require "$";
      Now, this seems to work using file spec:
      my $file = File::Spec->catfile( split /::/, $class ) . ".pm";
      Thanks for the time and tips,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://155443]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2018-07-17 12:20 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (363 votes). Check out past polls.