在这里doc中插入常量的首选方法是什么?

gcb*_*son 10 perl

我确信有几种方法可以在下面的<>中获取值'bar'进行插值,但最简洁的方法是什么,为什么?

use constant FOO => 'bar';

my $msg = <<EOF;
Foo is currently <whatever goes here to expand FOO>
EOF
Run Code Online (Sandbox Code Playgroud)

amo*_*mon 13

这里有两种文档:

  • <<'END',其行为大致类似于单引号字符串(但没有转义),以及
  • <<"END",<<END也就是说,它的行为类似于双引号字符串.

要在双引号字符串中插值,请使用标量变量:

my $foo = "bar";
my $msg = "Foo is currently $foo\n";
Run Code Online (Sandbox Code Playgroud)

或者使用arrayref插值技巧

use constant FOO => "bar";
my $msg = "Foo is currently @{[ FOO ]}\n";
Run Code Online (Sandbox Code Playgroud)

您还可以定义模板语言以替换正确的值.根据您的问题域,这可能会或可能不会更好:

my %vars = (FOO => "bar");
my $template = <<'END';
Foo is currently %FOO%;
END

(my $msg = $template) =~ s{%(\w+)%}{$vars{$1} // die "Unknown variable $1"}eg;
Run Code Online (Sandbox Code Playgroud)


Dav*_* W. 9

许多CPAN模块的问题是比use constantpragma 更好地执行常量,因为它们不是标准Perl包的一部分.不幸的是,在您可能不拥有的机器上下载CPAN模块可能非常困难.

因此,我决定坚持到use constantPerl开始包含类似Readonly标准模块的一部分(并且只有当像RedHat和Solaris这样的发行版决定更新到Perl的那些版本时.我仍然坚持使用5.8.8在我们的生产服务器上.)

幸运的是,你可以插入定义的常量,use constant如果你知道从黑客传递给黑客的神秘和神秘的咒语.

@{[...]}常数放在一边.这也适用于类中的方法:

use 5.12.0;
use constant {
    FOO => "This is my value of foo",
};

my $data =<<EOT;
this is my very long
value of my variable that
also happens to contain
the value of the constant
'FOO' which has the value
of @{[FOO]}
EOT

say $data;
Run Code Online (Sandbox Code Playgroud)

输出:

this is my very long
value of my variable that
also happens to contain
the value of the constant
'FOO' which has the value
of This is my value of foo

使用方法:

say "The employee's name is @{[$employee->Name]}";
Run Code Online (Sandbox Code Playgroud)

在旁边:

还有另一种方法可以使用我之前习惯使用的常量use constant.它是这样的:

*FOO = \"This is my value of foo";
our $FOO;

my $data =<<EOT;
this is my very long
value blah, blah, blah $FOO
EOT

say $data;
Run Code Online (Sandbox Code Playgroud)

您可以使用$FOO任何其他标量值,也不能修改它.您尝试修改该值,您将获得:

尝试修改只读值...


Sin*_*nür 4

使用Const::Fast代替Readonlyor constant。它们在没有任何扭曲的情况下进行插值。请参阅CPAN 模块来定义常量

对于条件编译,常量是一个不错的选择。它是一个成熟的模块并且被广泛使用。

...

如果您需要数组或哈希常量,或者不可变的丰富数据结构,请使用 Const::Fast。它与 Attribute::Constant 之间势均力敌,但 Const::Fast 似乎更成熟,并且发布了更多版本。

另一方面,您似乎正在编写自己的模板代码。不。相反,使用简单的东西,比如HTML::Template

use HTML::Template;

use constant FOO => 'bar';

my $tmpl = HTML::Template->new(scalarref => \ <<EOF
Foo is currently <TMPL_VAR VALUE>
EOF
);

$tmpl->param(VALUE => FOO);
print $tmpl->output;
Run Code Online (Sandbox Code Playgroud)