你需要有类似的东西:
文件:播放器.pm
package Player;
use strict;
use warnings;
sub new {
...
}
你的主脚本,connect4.pl
use strict;
use warnings;
use Player;
my $player = Player->new( ... args...);
编辑
首先只回答了上述问题,但基于事实,比你理解 perl 包应该如何组织有问题,恕我直言,你需要更多的 cmets,从 perl 初学者的角度来看(和我一样)。您可能会从 perl-guru 那里得到更好、更准确的答案。
如果您开始使用 perl 学习 OO,恕我直言,您应该开始使用 CPAN 中的“Mo”或“Moo”软件包。它们为您提供了一些不错的“糖”,极大地帮助您开始在 perl 中制作面向 OO 的程序,并允许您稍后将包扩展到 Moo? 的聪明兄弟 -> Moose。
必须说,这并不意味着您不需要学习 perl OO 的基本原理。
因为大多数 CPAN 模块都是在没有 Mo?se 的情况下编写的,而且您将阅读的许多程序都是用传统的 perl-OO 编写的,所以您仍然需要学习它,但是(来自我自己的经验)它需要更陡峭的学习曲线。你需要了解包的结构,什么是“blessing”等等。使用“Mo”(或 Moose)可以帮助您隐藏很多东西,稍后您将了解它们。
使用“Mo”可以帮助您在不完全理解的情况下获得更快的结果 - 为什么它会起作用。 ;) /现在许多 perl 专家可能会认为这是一种错误的学习方法。 :)/
使用“Mo”的播放器示例可以写成如下:
文件:播放器.pm
package Player;
use strict;
use warnings;
use Method::Signatures::Simple; # for automatic $self using "method" instead of the "sub"
use Mo;
has 'name';
has 'age';
method info {
return "The player " . $self->name . " is " . $self->age . " years old.";
}
1;
带有 main.pl 脚本的文件:
use strict;
use warnings;
use feature 'say';
use Player;
my $player = Player->new(name => 'John', age => 15);
say $player->info();
运行 main.pl 产生:
The player John is 15 years old.
如您所见,“Mo”为您提供了一种免费的“新”方法。 (以及许多其他事情)。
你真的需要阅读: