为什么 `exists` 会修改我的常量?
exists
函数可以 意外地自动激活哈希中的条目。
令我惊讶的是,这种行为也适用于常量:
use strict;
use warnings;
use Data::Dump 'dump';
use constant data => {
'foo' => {
'bar' => 'baz',
},
'a' => {
'b' => 'c',
}
};
dump data; # Pre-modified
print "No data for 'soda->cola->pop'\n" unless exists data->{soda}{cola}{pop};
dump data; # data->{soda}{cola} now sprung to life
输出
{ a =>; { b => "c" }, foo =>; { 栏 => “巴兹”}} 没有“苏打水->可乐->汽水”的数据 { 一个 => { b =>; "c" }, foo =>; { 栏 => “baz”},苏打水=> { 可乐 => {} } }
我怀疑这是一个错误。这是 5.10.1 特有的,还是其他版本的 Perl 行为类似?
The exists
function can unexpectedly autovivify entries in hashes.
What surprises me is that this behavior carries over to constants as well:
use strict;
use warnings;
use Data::Dump 'dump';
use constant data => {
'foo' => {
'bar' => 'baz',
},
'a' => {
'b' => 'c',
}
};
dump data; # Pre-modified
print "No data for 'soda->cola->pop'\n" unless exists data->{soda}{cola}{pop};
dump data; # data->{soda}{cola} now sprung to life
Output
{ a => { b => "c" }, foo => { bar => "baz" } } No data for 'soda->cola->pop' { a => { b => "c" }, foo => { bar => "baz" }, soda => { cola => {} } }
I suspect this is a bug. Is this something 5.10.1-specific, or do other versions of Perl behave similarly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是有记录的行为。 perldoc 常量 说:
不变的是引用,而不是它所指的内容。
This is documented behaviour. perldoc constant says:
It's the reference that is constant, not what it refers to.
您可能想使用 Readonly 来创建“true”常量。
使用
constant
编译指示创建的常量实际上是可内联子例程 。这意味着在编译时直接插入适当的标量常量来代替某些子例程调用。如果常量是引用,则没有什么可以阻止您更改它指向的数据。You probably want to use Readonly for creating "true" constants.
Constants created using the
constant
pragma are actually inlinable subroutines. It means that at compile time the appropriate scalar constant is inserted directly in place of some subroutine call. If the constant is a reference, nothing prevents you from changing the data it points to.