How to include a file that contains all the requir

2019-04-08 06:43发布

The perl scripts contain all the module names in the beginning of the script.

Ex:

use strict;
use XML::Parser;
use XML::Simple;
use DBI;
use DBD::DB2::Constants;
use POSIX qw( strftime );
use Storable qw(dclone);
use Data::Dumper;
use Carp;

How to keep all the module names in another file and include the file in main perl script ?

Thanks.

3条回答
手持菜刀,她持情操
2楼-- · 2019-04-08 07:18

You might look at the Toolkit module.

查看更多
SAY GOODBYE
3楼-- · 2019-04-08 07:31

You can use

BEGIN { do 'filename.pl' or die $@ }

See do. Be sure to include 1; at the bottom of the file.

查看更多
仙女界的扛把子
4楼-- · 2019-04-08 07:33

Create your own module. But, if if you make package in this module those strftime etc will be imported into another namespace. You can do litle hack to do this smiple:

MyModules.pm:

use strict;
use XML::Parser;
use XML::Simple;
use DBI;
use DBD::DB2::Constants;
use POSIX qw( strftime );
use Storable qw(dclone);
use Data::Dumper;
use Carp;

Note there was no package keyword in this .pm. Your script:

use MyModules;

Place this .pm into same dir with script or add modules search path at runtime:

use lib '/my_modules_dir/';
use MyModules;

Use of do and require commands is not recommended, since they do not check syntax on script start. Sure you can place them into BEGIN block but i think its tricky way and generally BEGIN{ require ..} is the same as use

UPD: ikegami noted problem its not working when you use this from many modules. Regardless question starter's information (he want to use this from main script), ill add info how to use this from many modules, so my friend can feel better. Add to end of MyModules.pm:

delete $INC{'MyModules.pm'};
1;
查看更多
登录 后发表回答