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

The following is a generalization, but hopefully it's clear enough.

I have a two packages, Foo::Bar and Foo::Batz. I have a sub called Plop which will create an object in one of these packages, based on it's argument in the statement. But the following code fails me, with a "Bad Name after Package::" error.
use strict; require 'foo_bar.pl'; #currently using require for these require 'foo_batz.pl'; #intention is to fold them into the #script after development my @Stack = (); my $type = "Bar" || "Batz"; do_phu($type); sub do_phu { my $class = shift; my $temp_obj = Foo::$type->new(); push( @Stack, $temp_obj ); # point of failure }
The answer to this is probably right in front of my face, but I'm stuck. I know there must be an alternative that doesn't involve a lot of if-thens.

Thanks in advance for any help!

Replies are listed 'Best First'.
Re: Scalar in Method Call
by Fastolfe (Vicar) on Dec 22, 2000 at 09:29 UTC
    I suspect it's complaining about your use of a variable within the module identifier (Foo::$type). The code there is ambiguous/bad. You probably want something like this (works in 5.6, not sure about earlier):
    my $temp_obj = "Foo::$type"->new(); # or, a more verbose version: no strict 'refs'; # because this isn't very strict my $temp_obj = &{"Foo::${type}::new"}("Foo::$type");
      Says fastolfe:
      no strict 'refs'; # because this isn't very strict my $temp_obj = "Foo::$type"->new();
      The no strict 'refs' is unnecessary here, since you aren't dealing with references of any sort. The code will run just fine under strict refs.

        You're right; it was the latter method that would have generated the error. I switched the order of the code around and neglected to move the 'no strict' with it.
      Quoting the construct alleviated the error, on to the other bugs. Thanks!
Re: Scalar in Method Call
by Anonymous Monk on Dec 23, 2000 at 01:56 UTC
    Here is the way I was shown, just put the module names into a hash reference:
    use strict; require 'foo_bar.pl'; #currently using require for these require 'foo_batz.pl'; #intention is to fold them into the #script after development my $mods = { 'Bar' => 'Foo::Bar', 'Batz' => 'Foo::Batz', }; my @Stack = (); my $type = "Bar" || "Batz"; do_phu($type); sub do_phu { my $class = shift; my $temp_obj = $mods->{$type}->new(); push( @Stack, $temp_obj ); # point of failure }