Using my with parentheses and only one variable

前端 未结 5 806
梦谈多话
梦谈多话 2020-12-01 00:37

I sometimes see Perl code like this:

my ( $variable ) = blah....

What is the point of putting parentheses around a single variable? I thou

5条回答
  •  情书的邮戳
    2020-12-01 01:31

    The parentheses create a list context which affects how the right hand side of the assignment is evaluated.

    Compare

    my $x = grep { /s/ } qw(apples bananas cherries);
    print $x;
    

    with

    my ($x) = grep { /s/ } qw(apples bananas cherries);
    print $x;
    

    You will often use this construction when you just want to grab the first element of a list and discard the rest.

提交回复
热议问题