如何将 Perl 匹配运算符中的匹配项提取到变量中? [英] How can I extract the matches from the Perl match operator into variables?

查看:40
本文介绍了如何将 Perl 匹配运算符中的匹配项提取到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个匹配运算符,我如何将括号中捕获的字符串部分保存在变量中,而不是使用 $1$2 等?

If I have a match operator, how do I save the parts of the strings captured in the parentheses in variables instead of using $1, $2, and so on?

... = m/stuff (.*) stuff/;

左边是什么?

推荐答案

诀窍是使用列表赋值让 m//在列表上下文中工作:

The trick is to make m// work in list context by using a list assignment:

 ($interesting) = $string =~ m/(interesting)/g;

这可以巧妙地扩展以获取更多东西,例如:

This can be neatly extended to grab more things, eg:

 ($interesting, $alsogood) = $string =~ m/(interesting) boring (alsogood)/g;

这篇关于如何将 Perl 匹配运算符中的匹配项提取到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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