Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I need to define multiple modules in the same file. 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?

like image 237
Robert S. Barnes Avatar asked Apr 12 '10 10:04

Robert S. Barnes


People also ask

How do you refer variable within a package in Perl?

The package stays in effect until either another package statement is invoked, or until the end of the current block or file. You can explicitly refer to variables within a package using the :: package qualifier.

What is the difference between package and module in Perl?

A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension . pm. Two different modules may contain a variable or a function of the same name.

How do I import a Perl file into another Perl file?

if you use “use” your file should be named with a . pm extension and placed in the same folder as the main perl script: use Filename; or you can use the “use lib” pragma to add modules to the @INC array and put them in any folder you want as long as you tell “lib” where you put your modules.


1 Answers

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.

like image 200
Dave Sherohman Avatar answered Sep 23 '22 03:09

Dave Sherohman