Perl: Difference between ($num) and $num [duplicat

2019-02-27 03:15发布

问题:

This question already has an answer here:

  • What's the difference between my ($variableName) and my $variableName in Perl? 4 answers

can someone please explain to me why this is diff:

my $num = '>33*1311875297587*eval*0*frame[0]*"A"<' =~ /(\d{3,})/;
> $num = 1
my ($num) = '>33*1311875297587*eval*0*frame[0]*"A"<' =~ /(\d{3,})/;
> $num = 1311875297587

I'm super curious to see what shenanigans are waiting for me.

Thanks

回答1:

In Perl, parentheses usually just alters precedence. (e.g. 3+4*5 vs (3+4)*5)

The exception is when parentheses are found on the left-hand side (LHS) of an assignment operator. In that situation, it influences which of Perl's two assignment operators will be used.

If the LHS of an assignment is some kind of aggregate, the list assignment is used. Otherwise, the scalar assignment is used. The following are considered to be aggregates:

  • (...) (any expression in parens)
  • @array and @array[...]
  • %hash and @hash{...}
  • my (...), our (...) and local (...) (state (...) throws an error.)

See Mini-Tutorial: Scalar vs List Assignment Operator for the differences between the two operators.

In your case, the relevant difference is the context in which the right-hand side (RHS) of the assignment is evaluated.

  • The scalar assignment evaluates its RHS operand in scalar context. In scalar context, the match operator returns a boolean value indicating success or failure.
  • The list assignment evaluates its RHS operand in list context. In list context, the match operator returns the strings it captured (or 1 if the match was successful and pattern contains no captures).