我应该使用 Internals::SvREADONLY 在 Perl 中创建只读变量吗?

发布于 2024-09-30 19:20:46 字数 374 浏览 2 评论 0原文

查看 Const::Fast 源代码 我注意到它在内部使用了内置函数Internals::SvREADONLY。直接在 Perl 脚本中使用该函数是否安全?它似乎存在于 Perl 5.8 的核心中。

my $PI = 4 * atan2 1, 1;
Internals::SvREADONLY($PI => 1);
$PI = 2.718;   # Modification of a read-only value attempted at ..

Looking into the Const::Fast source I noticed that it used the built-in function Internals::SvREADONLY internally. Is it safe to use that function directly in my Perl script? It seems to be present in core from Perl 5.8.

my $PI = 4 * atan2 1, 1;
Internals::SvREADONLY($PI => 1);
$PI = 2.718;   # Modification of a read-only value attempted at ..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

原谅过去的我 2024-10-07 19:20:46
C:\>perldoc Internals
No documentation found for "Internals".

不。

更具体地说,该包被命名为“Internals”是有原因的。它不适合在核心之外使用。它可能会发生变化,恕不另行通知。

C:\>perldoc Internals
No documentation found for "Internals".

No.

More specifically, the package is named "Internals" for a reason. It is not intended for use outside the core. It could change without notice.

随遇而安 2024-10-07 19:20:46

这并不能完全回答您的问题,但我认为值得一提,这样其他人就不会经历与我相同的痛苦:如果您在某个版本上运行,请不要使用任何只读值Perl 早于 5.10.1。考虑这个小例子:

{
    package Foo;
    sub foo { print "I'm in foo!\n"; }
}

use strict;
use warnings;
use Readonly;
Readonly my @classes => qw(Foo);

foreach my $class (@classes)
{
    # this dies with "Can't call method "foo" without a package or object reference"
    $class->foo;
}

由于我的 XS-fu 不是很高,所以我无法非常连贯地解释这里发生的事情(但是 Devel::Peek 在 $class 变量中显示了一些有趣的事情) 。

This is not quite answering your question, but I think it is worth mentioning so others don't experience the same pain as I have: don't use any readonly value if you're running on a version of Perl earlier than 5.10.1. Consider this little example:

{
    package Foo;
    sub foo { print "I'm in foo!\n"; }
}

use strict;
use warnings;
use Readonly;
Readonly my @classes => qw(Foo);

foreach my $class (@classes)
{
    # this dies with "Can't call method "foo" without a package or object reference"
    $class->foo;
}

Since my XS-fu is not very high, I can't explain what is going on here very coherently (but Devel::Peek shows some interesting things in the $class variable).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文