我有4个文件。
start.pl6用于运行我的程序。 3个模块文件包含或生成最终由start.pl6使用的数据。我使用atom.io来运行代码。
以下是代码:
start.pl6:
use v6;
use lib ".";
use file0;
use lib "folder1";
use file1;
use lib "folder2";
use file2;
say 'start';
my $file0 = file0.new();
say $file0.mystr;
my $file1 = file1.new();
say $file1.mystr;
my $file2 = file2.new();
say $file2.mystr;
say 'end';
file0.pm6:
class file0 is export {
has Str $.mystr = "file 0";
submethod BUILD() {
say "hello file 0";
}
}
file1.pm6:
class file1 is export {
has Str $.mystr = "file 1";
}
file2.pm6:
class file2 is export {
has Str $.mystr = "file 2";
}
输出:
start
hello file 0
file 0
file 1
file 2
end
[Finished in 0.51s]
我不想在start.pl6中创建所有3个模块文件的实例,而是想在file1中创建file2的实例,在file0中创建file1的实例。这样我只需要在start.pl6中创建一个file0实例来查看相同的输出;
以下是我的想法:
file1.pm6:
use lib "../folder2";
use "file2.pl6";
class file1 is export {
has Str $.mystr = "file 1";
submethod BUILD() {
my $file2 = file2.new();
$!mystr = $!mystr ~ "\n" ~ $file2.mystr;
# I want to instantiate file2 inside the constructor,
# so I can be sure the line
# $!mystr = $!mystr ~ "\n" ~ $file2.mystr;
# takes effect before i call any of file0's methods;
}
}
file0.pm6:
use lib "folder1";
use "file1.pl6";
class file0 is export {
has Str $.mystr = "file 0";
submethod BUILD() {
say "hello file 0";
my $file1 = file1.new();
$!mystr = $!mystr ~ "\n" ~ $file1.mystr;
}
}
在file0中,行 使用lib" folder1&#34 ;; 使用" file1.pl6&#34 ;; 产生此错误:
===SORRY!=== Error while compiling C:\perlCode2\file0.pm6 (file0)
'use lib' may not be pre-compiled
at C:\perlCode2\file0.pm6 (file0):2
------> use lib "folder1/file1.pl6"<HERE>;
[Finished in 0.584s]
我是file1,这一行 使用lib&#34; ../ folder2&#34 ;; 使用&#34; file2&#34 ;; 不起作用,但也没有给出错误。我得到输出: [完成0.31秒]
最后,文件start.pl6应该如下所示产生输出:
start.pl6:
use v6;
use lib ".";
use file0;
say 'start';
my $file0 = file0.new();
say $file0.mystr;
say 'end';
输出:
start
hello file 0
file 0
file 1
file 2
end
答案 0 :(得分:2)
你要做的事对我来说毫无意义。您似乎正在将这些模块随意放入文件夹中。
如果这些模块的名称确实有意义,我可以如何构建它。
C:\perlCode2\start.pl6
C:\perlCode2\lib\file0.pm6
C:\perlCode2\lib\folder1\file1.pm6
C:\perlCode2\lib\folder2\file2.pm6
start.pl6 :
use v6;
END say "[Finished in {(now - $*INIT-INSTANT).fmt("%0.2fs")}";
use lib 'lib';
use file0;
say 'start';
my $file0 = file0.new;
say $file0.mystr;
say 'end';
LIB \ file0.pm6 :
use folder1::file1;
class file0 is export {
has Str $.mystr = "file 0";
submethod TWEAK() {
say "hello file 0";
$!mystr ~= "\n" ~ folder1::file1.new.mystr;
}
}
LIB \ folder1中\ file1.pm6 :
use folder2::file2;
class folder1::file1 is export {
has Str $.mystr = "file 1";
submethod TWEAK() {
$!mystr ~= "\n" ~ folder2::file2.new.mystr;
}
}
LIB \文件夹2 \ file2.pm6
class folder2::file2 is export {
has Str $.mystr = "file 2";
}
答案 1 :(得分:1)
use lib "folder2/file2.pl6";
这不符合你的想法。 use lib需要一个目录,其中Perl应该寻找模块,而不是某些脚本的路径。
如果您的My.pm6位于./lib(相对于当前工作目录),那么
use lib "lib";
use My;
诀窍。您也可以使用绝对路径
use lib "~/projects/perl6/MyProject/lib";
use My;
请参阅lib。