我遇到了一個問題,我的程序將無限循環。我縮小了這個問題,事實證明,關鍵字要求是造成這一點。因此,爲了理解這個問題,我編寫了一個簡單的hello world程序,它具有包含更大程序的確切文件結構。它有一個主文件test.pl它從test2.pm調用helloWorld。 test2.pm調用與test1.pm相同的例程。Perl關鍵字要求給出了奇怪的結果
Test.pl
#!/usr/bin/perl
use test1;
use test2;
print "In test\n";
test2::helloWorld();
Test1.pm
#!/usr/bin/perl
package test1;
use test2;
require "test.pl";
@ISA = qw (Exporter);
@Export = qw(
helloWorld
);
sub helloWorld {
print "Hello world: Test1\n";
}
Test2.pm:
#!/usr/bin/perl
package test2;
use test1;
@ISA = qw (Exporter);
@Export = qw(
helloWorld
);
sub helloWorld {
test1::helloWorld();
}
這是從程序的輸出:
In test
Hello world: Test1
In test
Hello world: Test1
我想了解爲什麼它打印輸出兩次?如果我從test1.pm註釋掉 #require「test.pl」,它只打印輸出一次。
Test1.pm(需要行註釋掉)
#!/usr/bin/perl
package test1;
use test2;
#require "test.pl";
@ISA = qw (Exporter);
@Export = qw(
helloWorld
);
sub helloWorld {
print "Hello world: Test1\n";
}
而這正是現在輸出:
In test
Hello world: Test1
我想如果我理解這一點,我可以解決我的真正的問題。感謝您在這方面:)
比我的更好的解釋。 – Schwern 2012-03-20 19:41:43
感謝您的解釋......它幫助了很多。我只想再問一件事。正如你在步驟2.2中提到的那樣,它會打印'in test'並調用'test2 :: helloWorld'。但是爲什麼它首先打印並調用函數呢?關鍵字'require'僅用於INLCLUDE文件不執行它?這是不正確的? – Richeek 2012-03-20 21:04:21
'require'編譯*和*運行(使用''也是如此)。 'require'只是讀取文件和'eval'內容,而不是一次。否則像'@ISA = qw(Exporter)'這樣的事情''不會發生。 – Schwern 2012-03-21 04:55:56