Perl 和之间的差异%p';和';我的%p';? %%p=('option1'=>'option1', %'选项2'=>'选项2', %“选项3”=>“选项3” % ); %foreach(键%p){ %我的$selected=param('killer\u feature')和¶m('killer\u feature')eq$\u?'selected=“selected”:; %如果(!param('killer_feature')&&$$eq'option2'){$selected='selected=“selected”} % }
上面的代码通过返回“Internal server error”(内部服务器错误)中断了应用程序,但是如果我将第一行smiply编辑为Perl 和之间的差异%p';和';我的%p';? %%p=('option1'=>'option1', %'选项2'=>'选项2', %“选项3”=>“选项3” % ); %foreach(键%p){ %我的$selected=param('killer\u feature')和¶m('killer\u feature')eq$\u?'selected=“selected”:; %如果(!param('killer_feature')&&$$eq'option2'){$selected='selected=“selected”} % },perl,mojo,mojolicious,Perl,Mojo,Mojolicious,上面的代码通过返回“Internal server error”(内部服务器错误)中断了应用程序,但是如果我将第一行smiply编辑为%my%p(我尝试了它,因为其他一些控件具有此格式),我想知道这两者之间的区别是什么 它是一个基于Mojolicous web框架构建的perl应用程序 非常感谢 Raw%p表示使用全局(包)变量“%p”。为了更具技术性,默认情况下,未声明的变量名被视为包变量,并以静默方式与当前包的名称挂起-例如,它实际上是指%main::p变量,因为默认情况下您位于主包中 但是
%my%p
(我尝试了它,因为其他一些控件具有此格式),我想知道这两者之间的区别是什么
它是一个基于Mojolicous web框架构建的perl应用程序
非常感谢 Raw
%p
表示使用全局(包)变量“%p”。为了更具技术性,默认情况下,未声明的变量名被视为包变量,并以静默方式与当前包的名称挂起-例如,它实际上是指%main::p
变量,因为默认情况下您位于主包中
但是如果解释器在启用了使用strict
pragma的情况下运行Perl代码(就像mojo一样),则不会自动将当前包名预挂起到未声明的变量,因此,带有这样一个变量的代码将不会编译,因为从词法范围声明或包符号表中实际上不知道变量%p
添加my
将“%p”变量声明到本地(词法)范围中,现在它将很高兴地满足strict
pragma
Randal Schwartz的Stonehendge咨询网站提供了关于Perl中变量作用域的更深入(且编写得更好)的解释:您真正的问题似乎是:什么是
my
关键字,为什么需要它
my
用于在局部范围内声明变量,也可在局部声明子例程:
% %p = ('option1' => 'Option 1',
% 'option2' => 'Option 2',
% 'option3' => 'Option 3'
% );
<select name="killer_feature" id="killer_feature" class="select">
% foreach (keys %p) {
% my $selected = param('killer_feature') && param('killer_feature') eq $_ ? 'selected="selected"' : '';
% if (!param('killer_feature') && $_ eq 'option2') { $selected = 'selected="selected"' }
<option value=" <%=$_%>" <%= $selected %>>
<%= $p{$_} %>
</option>
% }
</select>
因为Mojolicious使用了use strict
,所以它要求用(my
,our
,local
等)声明所有变量
注意在上面的代码中多次使用my
时会发生什么。它不必要地重新声明变量,覆盖先前分配的内容
与大多数编程语言一样,只需声明一次变量,然后在必要时再次使用该变量。但我想知道为什么同一文件中的某些其他元素会使用
%%p
而不会出错?一旦在文件顶部声明一次,它的词法范围将扩展到文件的末尾。此外,开始“%”是完全不相关的-这只是mojo知道某些东西是模板的Perl代码而不是HTML的一种方式
#!/usr/bin/perl
use strict;
my $foo = "defined in outer";
print_result ("outer",$foo); # outer: defined in outer
{
# $foo has not yet been defined locally
print_result ("inner",$foo); # inner: defined in outer
my $foo = "defined in inner"; # defining $foo locally
print_result ("inner",$foo); # inner: defined in inner
my $foo; # re-declaring $foo
print_result ("inner", $foo); # inner:
}
# even though $foo was defined in the subroutine, it did not
# override the $foo outside the subroutine (localization occured)
print_result ("outer",$foo); # main: defined in main
sub print_result {
my ($proc,$value) = @_;
print qq{$proc:\t$value\n};
}