Perl中my($ variableName)和my $ variableName之间的区别是什么?

Joh*_*n 23 perl

Perl my ($variableName)my $variableNamePerl有什么区别?括号怎么办?

mob*_*mob 20

重要的效果是在声明变量的同时初始化变量:

my ($a) = @b;   # assigns  $a = $b[0]
my $a = @b;     # assigns  $a = scalar @b (length of @b)
Run Code Online (Sandbox Code Playgroud)

另一个重要的是当你声明多个变量时.

my ($a,$b,$c);  # correct, all variables are lexically scoped now
my $a,$b,$c;    # $a is now lexically scoped, but $b and $c are not
Run Code Online (Sandbox Code Playgroud)

如果你,最后一句话会给你一个错误use strict.

  • 所以本质上:括号1.提供列表上下文,以及2.跨多个值分配运算符或函数. (10认同)
  • #1也不完全正确.赋值左侧的parens提供了列表上下文,但这并不意味着它们在其他地方提供列表上下文. (3认同)
  • #2在技术上是不正确的,可能会产生误导.这是不正确的,因为parens声明的工作方式是定义词汇列表而不是词法标量.它是误导性的,初学者可能会读到"括号......在多个值之间分配运算符或函数",并期望`($ x,$ y)=(1,2)+ 3`将值4赋值给` $ x`和5到`$ y`通过"在多个值上分配+运算符".(实际上,该语句将5分配给`$ x`而不分配给'$ y`.) (2认同)

gho*_*g74 5

有关运营商的更多信息,请查看perdoc perlsubmy.这是一个小摘录:

概要:

   my $foo;            # declare $foo lexically local
   my (@wid, %get);    # declare list of variables local
   my $foo = "flurp";  # declare $foo lexical, and init it
   my @oof = @bar;     # declare @oof lexical, and init it
   my $x : Foo = $y;   # similar, with an attribute applied
Run Code Online (Sandbox Code Playgroud)


EmF*_*mFi 5

简短的回答是,当在左侧使用括号时强制列表上下文=.

每个其他答案都指出了一个具体的案例,这会产生影响.实际上,您应该通读perlfunc以更好地了解在列表上下文中调用时函数的行为方式与标量上下文相反.