我在perl中有一个共享模块.主程序需要两个文件,第一个是共享文件(让我们称之为’X’),第二个是’包’文件.文件’X’也使用’require’包含在’package’文件中.当我编译这个程序时,它给我以下错误:
Undefined subroutine &main::trim called at testing.pl line 8.
我的理解是perl找不到trim()模块.如果我不包含包文件,那么这将运行没有任何问题.
任何人都可以解释这个问题吗?
这些是我的代码:
主程序:testing.pl
#!/usr/bin/perl -w use strict; use postgres; require "shared.pl"; trim("als");
包文件:postgres.pm
#!/usr/bin/perl package postgres; use strict; use DBI; require "shared.pl"; 1;
共享文件:shared.pl
#!/usr/bin/perl # ============= # shared module # ============= use strict; sub trim($) { } 1;
解决方法
默认情况下,require只会加载一次文件.在这种情况下,那一次来自postgres包中的文件postgres.pm.因此trim子程序在postgres名称空间中定义为& postgres :: trim.
一种解决方法是在testing.pl文件中使用完全限定的子例程名称:
postgres::trim("als"); # not trim("als")
另一个解决方法是破解%INC
表(跟踪已使用和需要的模块/文件的变量),以便您可以将shared.pl重新加载到主程序包中:
use postgres; delete $INC{"shared.pl"}; require "shared.pl";
第三种解决方法是将trim函数从postgres包导出到主包. Exporter
模块的文档很好地介绍了为什么以及如何完成.
# in postgres.pm *main::trim = *trim; # or in testing.pl *trim = *postgres::trim; trim("als");