在Perl中,如何将多个类放在单个.pm文件中

时间:2017-09-28 15:39:38

标签: perl moose

我有一个关于Perl MooseX::Declare的问题。我想在一个.pm文件中放置多个类。我如何制作这个文件,文件名是什么,因为.pm文件有多个类?

例如

use MooseX::Declare;
class Point {

   has 'x' => ( isa => 'Num', is => 'rw' );
   has 'y' => ( isa => 'Num', is => 'rw' );

   method clear {
      $self->x(0);
      $self->y(0);
   }
   method set_to( Num $x, Num $y) {
      $self->x($x);
      $self->y($y);
   }
}


class Point3D {

   has 'z' => ( isa => 'Num', is => 'rw' );

   method clear {
      $self->z(0);
   }
   method set_to( Num $x, Num $y, Num $z) {
      $self->x($x);
      $self->y($y);
      $self->z($z);
   }
}

如何保存此pm文件 - 按头等名称或第二类名称?

2 个答案:

答案 0 :(得分:4)

由于每个单一文件的指南仅用于帮助您组织自己的代码,因此您可以将文件命名为您想要的任何内容。

那就是说,指南存在的充分理由。

perlmonks您可能想要查看有关此主题的有趣讨论。

我建议不要对每个文件使用多个类,除非你将它们放在一个公共命名空间中。

{
    package Geometrics;

    class Point {
        ...
    }

    class Point3D {
        ...
    }
}

如果你走那条路,你可以相应地命名你的.pm文件(即Geometrics.pm)。

如果不这样做,假设你的课程与主题相关(就像它们似乎那样),那么Points.pm之类的东西也许是恰当的。

修改

至于如何“从外部调用或使用类(Point,Point3D)”或如何实例化模块中定义的类:

# import the package
use Geometrics qw(Point Point3d);
# or
# use Geometrics ('Point' 'Point3d');


# instantiate a Point
my $point = Point->new();

# instantiate a Point3D
my $point3d = Point3D->new();

您也可以通过以下任一方式导入包:

# import the package but do not import any symbols from it
use Geometrics ();

# While you can import the package this way, please do not do so.
# import the package with ALL symbols
use Geometrics;

但这样做会有一些警告......

# importing the package with no symbols
use Geometrics ();

# means instantiation of objects must be fully-qualified
my $point = Geometrics::Point->new();
my $point3d = Geometrics::Point3D->new();
# importing the package with ALL symbols
use Geometrics;

# makes instantiation of objects simpler
my $point = Point->new();
my $point3d = Point3D->new();

# BUT because all symbols are imported with the package,
# overwriting of symbols can occur too easily.
# If I were to import the package Foo this way (which has the symbol Bar defined)
use Foo;

# and then import the package Baz this way (which also has the symbol Bar defined)
use Baz;

# I no longer have access to Foo:Bar as that has been over-written by Baz::Bar
# because I imported the packages with ALL symbols by default.
# The lesson here is to code defensively and:
#     only import those symbols you intend to use, or
#     don't import any symbols and fully-qualify everything.

答案 1 :(得分:0)

作为一般规则,不要在一个文件中放置多个类。

我以前经常看到的异常是相关类,尤其是顶级类的辅助类或子类。在这些情况下,它们总是被分组到一个包中,文件名是包名。