Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Runtime instantiation decisions

by Kanji (Parson)
on Mar 30, 2002 at 17:02 UTC ( [id://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( @_ ); }

Update:

... 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( @_ ); }

    --k.


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 "$file.pm";
      Now, this seems to work using file spec:
      my $file = File::Spec->catfile( split /::/, $class ) . ".pm";
      Thanks for the time and tips,
      LogicalChaos

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://155443]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-23 15:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found