+ -
当前位置:首页 → 问答吧 → package 中的函数都要加上命名空间吗?

package 中的函数都要加上命名空间吗?

时间:2011-02-01

来源:互联网

本帖最后由 yakczh 于 2011-02-01 12:52 编辑

我写了一个package 里面的函数用到md5

比如
  1. use Digest::MD5 qw(md5 md5_hex md5_base64);
  2. package Utils;

  3. sub  aaa{
  4.    my $str=shift;
  5.    return md5_hex($str);
  6. }
复制代码
然后在另个perl文件中 require这个包

a.pl
  1. require "Utils.pm";

  2. print Utils::aaa("som");
复制代码
提示  Undefined subroutine &Utils::md5_hex called at Utils.pm

作者: yakczh   发布时间: 2011-02-01

package里这2句调一下顺序:
  1. package Utils;
  2. use Digest::MD5 qw(md5 md5_hex md5_base64);
复制代码
要理解什么是“包”。

作者: 兰花仙子   发布时间: 2011-02-01

本帖最后由 yakczh 于 2011-02-01 12:53 编辑

包应该起命名空间的作用吧

还有自己写包的话 一个包最后都要写上一句
  1. 1;
复制代码
不然导入包的文件会提示
Utils.pm did not return a true value at :

这是什么道理

作者: yakczh   发布时间: 2011-02-01

本帖最后由 zhlong8 于 2011-02-01 13:54 编辑

perldoc -f require 中有这么一句


QUOTE:
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1; , in case you add more statements.


其中给的等效代码用的是
  1. $result = do $realfilename;
复制代码
而 do 返回 undef 表示失败,否则返回最后表达式的值


QUOTE:
If do cannot read the file, it returns undef and sets $! to the error. If do can read the file but cannot compile it, it returns undef and sets an error message in $@ . If the file is successfully compiled, do returns the value of the last expression evaluated.


其中 require 的等效代码只检测了 $@ 编译错误,而没有检查 $!  表示的 IO 错误

require 的错误处理是这样的
  1.        if ($@) {
  2.            $INC{$filename} = undef;
  3.            die $@;
  4.        } elsif (!$result) {
  5.            delete $INC{$filename};
  6.            die "$filename did not return true value";
  7.        } else {
  8.            return $result;
  9.        }
复制代码
意味着编译错误即使被捕获也不会重新导入了,因为没有 delete $INC{$filename},而下面的 $result 则表明是 IO 错误,如果被捕获还可以重新导入相应模块。至于 require 为什么不直接检测 $! 我也不明白现在

作者: zhlong8   发布时间: 2011-02-01