为什么在此 Perl 片段中分配正则表达式匹配的返回值时标量周围有括号? [英] Why are there parentheses around scalar when assigning the return value of regex match in this Perl snippet?

查看:37
本文介绍了为什么在此 Perl 片段中分配正则表达式匹配的返回值时标量周围有括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了从字符串中获取数字,我编写了以下正则表达式:

I wrote the following regex in order to get the digits from a string:

my ($digits) = ($str =~ /(\d+)/);

它按预期工作,但我想知道为什么我需要在 $digits 周围使用括号?为什么没有括号它不起作用?我试图在网上找到一些关于它的信息,但没有找到.

It works as expected but I was wondering why I need to use parentheses around $digits? Why doesn't it work without the parenthesis? I tried to find some information about it on the web but didn't find any.

为什么我可以这样使用它:

Why can I use it like this:

my $digits = ($str =~ /(\d+)/);

我可以对 $str 进行更改吗?像这样: $str =~/(\d+)/;?

Can I make the changes on the $str? something like this: $str =~ /(\d+)/;?

推荐答案

= 表示有两个赋值运算符:

There are two assignment operators denoted by =:

  • 标量赋值运算符.
  • 列表赋值运算符.

Perl 根据赋值的左侧 (LHS) 是否是某种聚合来决定使用哪个.以下被认为是聚合,导致使用列表赋值运算符:

Perl decides which one to use based on whether the left-hand side (LHS) of the assignment is some kind of aggregate or not. The following are considered to be aggregates, which result in the use of the list assignment operator:

  • (...)(括号中的任何表达式)
  • @array
  • @array[...]
  • %hash
  • @hash{...}
  • myourlocal
  • 开头的任何上述内容
  • (...) (any expression in parentheses)
  • @array
  • @array[...]
  • %hash
  • @hash{...}
  • Any of the above preceded by my, our or local

运算符之间有两个区别.

There are two differences between the operators.

第一个是计算其操作数的上下文.

The first is the context in which its operands are evaluated.

  • 标量赋值在标量上下文中计算其两个操作数.
  • 列表赋值在列表上下文中评估它的两个操作数.

第二个区别是它们返回的内容.

The second difference is what they return.

  • 标量赋值将 LHS 计算为左值.
  • 标量上下文中的列表分配计算为 RHS 返回的标量数.
  • 列表上下文中的列表赋值计算为 LHS 作为左值返回的标量.

示例可在此处找到.

第一个区别对您来说很重要.

The first difference is the one that matters in your case.

  • my $digits = $str =~/(\d+)/; 使用标量赋值运算符,它计算 $str =~/(\d+)//(\d+)/ 在标量上下文中.在标量上下文中,/(\d+)/ 和因此 $str =~/(\d+)/ 评估匹配是否成功.

  • my $digits = $str =~ /(\d+)/; uses the scalar assignment operator, which evaluates $str =~ /(\d+)/ and thus /(\d+)/ in scalar context. In scalar context, /(\d+)/ and thus $str =~ /(\d+)/ evaluates to whether the match was successful or not.

my ($digits) = $str =~/(\d+)/; 使用列表赋值运算符,它计算 $str =~/(\d+)//(\d+)/ 在列表上下文中.在列表上下文中, /(\d+)/$str =~/(\d+)/ 计算为匹配捕获的字符串.

my ($digits) = $str =~ /(\d+)/; uses the list assignment operator, which evaluates $str =~ /(\d+)/ and thus /(\d+)/ in list context. In list context, /(\d+)/ and thus $str =~ /(\d+)/ evaluates to the strings captured by the match.

这篇关于为什么在此 Perl 片段中分配正则表达式匹配的返回值时标量周围有括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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