“标准"和“标准"之间有什么区别吗?和块包声明? [英] Is there any difference between "standard" and block package declaration?

查看:48
本文介绍了“标准"和“标准"之间有什么区别吗?和块包声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,一个包的开头很简单

Usually, a package starts simply as

package Cat;
... #content
!0;

我刚刚发现从 perl 5.14 开始也有块"语法.

I just discovered that starting from the perl 5.14 there is the "block" syntax too.

package Cat {
    ... #content
}

应该是一样的.但可以肯定的是,是否有任何区别?

It is probably the same. But just to be sure, is there any difference?

关于包文件末尾的1;.任何块的返回值都被视为最后一个评估表达式的值.那么我可以将 1; 放在结束 } 之前吗?为了让 require 开心,有什么区别:

And about the 1; at the end of the package file. The return value of any block, is taken as the value of the last evaluated expression. So can I put the 1; before the closing }? To make require happy, is there any difference between:

package Cat {
    ... #content
    1; 
}

package Cat {
    ... #content 
}
1;

推荐答案

当然是有区别的.第二个变体有一个.

Of course there is a difference. The second variant has a block.

package 声明为 subs 和 globals 设置当前命名空间.这是正常范围的,即范围以文件结尾或 eval 字符串结尾,或者以封闭块结尾.

A package declaration sets the current namespace for subs and globals. This is scoped normally, i.e. the scope ends with the end of file or eval string, or with an enclosing block.

package NAME BLOCK 语法只是语法糖

{ package NAME;
  ...;
}

甚至编译成相同操作码.

虽然 package 声明在语法上是一个声明,但在语义上却不是这样;它只是设置编译时属性.所以最后一块的最后一条语句就是文件的最后一条语句,和

While the package declaration is syntactically a statement, this isn't semantically true; it just sets compile-time properties. Therefore, the last statement of the last block is the last statement of the file, and there is no difference between

package Foo;
1;

package Foo {
  1;
}

说.最后一句话.

package BLOCK 语法很有趣,主要是因为它看起来像其他语言中的 class Foo {},我认为.由于块限制了作用域,这也使得使用适当作用域的变量变得更加容易.认为:

The package BLOCK syntax is interesting mainly because it looks like class Foo {} in other languages, I think. Because the block limits scope, this also makes using properly scoped variables easier. Think:

package Foo;
our $x = 1;
package main;
$::x = 42;
say $x;

输出:1,因为our 的词法范围和my 一样,只是声明了一个别名!这可以通过块语法来防止:

Output: 1, because our is lexically scoped like my and just declares an alias! This can be prevented by the block syntax:

package Foo {
  our $x = 1;
}
package main {
  $::x = 42;
  say $x;
}

按预期工作 (42),尽管 strict 不满意.

works as expected (42), although strict isn't happy.

这篇关于“标准"和“标准"之间有什么区别吗?和块包声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆