使用带括号和只有一个变量的 my [英] Using my with parentheses and only one variable

查看:21
本文介绍了使用带括号和只有一个变量的 my的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时会看到这样的 Perl 代码:

I sometimes see Perl code like this:

my ( $variable ) = blah....

在单个变量周围加上括号有什么意义?我认为括号只在声明多个变量时使用,例如:

What is the point of putting parentheses around a single variable? I thought parentheses were only used when declaring multiple variables, like:

my ( $var1, $var2, $var3 ) = blah...

推荐答案

出现差异时有几种情况:

There are several scenarios when there is a difference:

  1. array 在右侧时

my @array = ('a', 'b', 'c');
my  $variable  = @array;           #  3   size of @array
my ($variable) = @array;           # 'a'  $array[0]

  • 列表在右侧时

    my  $variable  = qw/ a b c d /;    # 'd'  last  item of the list
    my ($variable) = qw/ a b c d /;    # 'a'  first item of the list
    

  • 带有变量(数组/标量)返回值的子程序

    sub myFunction {
      ...
      return (wantarray() ? @array : $scalar);
    }
    my  $variable  = myFunction(...);  # $scalar   from the subroutine
    my ($variable) = myFunction(...);  # $array[0] from the subroutine
    

  • 这篇关于使用带括号和只有一个变量的 my的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆