Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

perl - Using my with parentheses and only one variable

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...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are several scenarios when there is a difference:

  1. When array is on right side

    my @array = ('a', 'b', 'c');
    my  $variable  = @array;           #  3   size of @array
    my ($variable) = @array;           # 'a'  $array[0]
    
  2. When list is on right side

    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
    
  3. Subroutine with variable (array/scalar) return value

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...