代码之家  ›  专栏  ›  技术社区  ›  eozzy

“%p”和“我的%p”之间的差异?

  •  3
  • eozzy  · 技术社区  · 15 年前
    % %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>
    

    % my %p (我试过了,因为其他一些控件有这种格式)它可以工作,我想知道两者之间有什么区别。

    非常感谢!

    2 回复  |  直到 15 年前
        1
  •  8
  •   DVK    15 年前

    生的 %p 表示使用全局(包)变量“%p”。更专业的是,默认情况下,未声明的变量名被视为包变量,并以静默方式与当前包的名称预先挂起-例如,它实际上是指 %main::p

    但是 如果Perl代码是由解释器使用 use strict %第 实际上从词法范围声明或包符号表中都不知道。

    添加 my strict 布拉格马。

    Randal Schwartz的Stonehendge consulting网站提供了关于Perl中变量作用域的更深入(更完善)的解释: http://www.stonehenge.com/merlyn/UnixReview/col46.html

        2
  •  2
  •   vol7ron    15 年前

    看来你真正的问题是: my 关键字以及为什么需要它?

    用于在局部范围内声明变量,也可在局部声明子例程:

    #!/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};
       }
    

    因为Mojolicous使用 use strict 我的 , our , local 等)。

    注意当你使用 我的

    与大多数编程语言一样,只需声明一次变量,然后根据需要再次使用该变量。