Robert S. Barnes Robert S. Barnes - 5 months ago 10
Perl Question

How can I call a Perl package I define in the same file?

I need to define some modules and use them all in the same file. No, I can't change the requirement.

I would like to do something like the following:

{
package FooObj;

sub new { ... }

sub add_data { ... }
}

{
package BarObj;

use FooObj;

sub new {
...
# BarObj "has a" FooObj
my $self = ( myFoo => FooObj->new() );
...
}

sub some_method { ... }
}

my $bar = BarObj->new();


However, this results in the message:


Can't locate FooObj.pm in @INC ...

BEGIN failed...


How do I get this to work?

Answer

Drop the use. Seriously.

use tells perl to read in the code from another file, which you don't need to do because the code is in the same file.