2011-03-13 21 views
28

如果您忘記包裝末尾的1,Perl會告訴您「包裝沒有返回真實值」。那麼,如果它知道你忘了它,爲什麼不把它放在那裏呢?爲什麼1在每個perl包的末尾?

+2

你想[真](http://p3rl.org/true)。 – daxim

回答

34

因爲如果require指令必須成功(返回true值)或失敗(返回false值;如果模塊由於某種原因未能初始化),則需要Perl模塊返回值以發出信號。

如果您不返回任何內容,解釋器無法知道require必須成功還是失敗;同時,由於很容易忘記將真正的價值放在包裝的末尾,它暗示了這種錯誤的「常見問題」:添加一個真正的價值作爲回報。

對於其他有關模塊返回值的其他信息/民間傳說看看this question

+0

如果你忘了放在那裏,那是不是意味着你可能不需要發出任何失敗的初始化信號?既然它看起來會是一個非常專業化的案例,我們不能否認它會成功,除非我們告訴它它有可能不會成功? –

+3

@Chris:我們可以爭論什麼會更好或更合乎邏輯,但語言是以這種方式設計的,談論它並不會改變這種行爲。 ':)'(個人來說,我認爲它現在更好一些:如果要求返回值,那麼你*有*來指定它) –

+1

@Matteo - 由於Perl 6仍然處於「無限期未來」階段我認爲談論語言_can_(幾乎肯定會)會改變它的行爲。 –

4

如果程序包無法初始化,例如無法找到所需的數據文件或外部程序庫,則該程序包可能會返回錯誤的值。這種方式在加載時會乾淨地失敗(甚至可以測試此失敗),而不是在以後不可預知的情況下。

+0

如果程序包未能初始化,它可能會返回一個錯誤的值,但它不應該。用有用的信息來消磨會更好。 – ikegami

2

1;

When a module is loaded (via use) the compiler will complain unless the last statement executed when it is loaded is true. This line ensures that this is the case (as long as you don't place any code after this line). It's Perl's way of making sure that it successfully parsed all the way to the end of the file.

http://mathforum.org/~ken/perl_modules.html

您可以使用評估爲真任何聲明。 1恰好成了一個perl習語。

3

wikipedia Perl module

A Perl module must end with a true value or else it is considered not to 
    have loaded. By convention this value is usually 1 though it can be 
    any true value. A module can end with false to indicate failure but 
    this is rarely used and it would instead die() (exit with an error). 
相關問題