[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] Safely instantiate (or not) a class that may or may not exist?



[Attempt #1 to describe my problem.]

Howdy! I've got a chuck of code. For most partner_id's, I have an
OutboundHeader. For some, though, I don't. So I'm trying to safely trap
the possible non-existance using eval like so:

   my $class = "${namespace}::${partner_id}::OutboundHeader";
   my $obj;
   eval($obj = $class->new(Globals=>$self->Globals));
   return 0 if $@;   # Header doesn't exist, so skip it.

But, no joy. It still pukes out on me:

Can't locate object method "new" via package
"Model::Rewards::Record::AA::OutboundHeader" (perhaps you forgot to load
"Model::Rewards::Record::AA::OutboundHeader"?) at
/usr/lib/perl5/site_perl/Omni/MVC/Model/Rewards/File.pm line 428.

How can I ask Perl if it can find a class, and skip instantiation if it
can't find it?



[Attempt #2 to describe my problem.]

This bombs out if there isn't a package "X" with a subroutine "new()":

my $class = "X";
my $obj = $class->new();

For any given $class that may or may not exist, how can I ask Perl IF
$class->new() is going fatal error or not, w/o a fatal error actually
occuring? My attempt at eval() failed...



[The solution from IRC]

I was using eval() wrong. Curly braces are required/best. This works:

   my $class = "${namespace}::${partner_id}::OutboundHeader";
   my $obj;
   eval { $obj = $class->new(Globals=>$self->Globals) };
   return 0 if $@;   # Header doesn't exist, so skip it.

I still fear the black magic of eval(). -grin-

j