如何在Perl中设置变量中的文本

问题描述 投票:-8回答:1

我有一个文本字符串,我想搜索一个单词。

我需要为找到的单词设置一个变量。

我的文字是Cat dog Jim NY You

我的搜索词是NY

我需要将匹配的子字符串放入变量中。

#!/usr/bin/perl

$x = "Cat dog Jim NY You";

if ( $x=~/NY/ ) {
    print "???\n";
}
regex perl
1个回答
2
投票

使用捕获((...))。

if ( my ($capture) = $x =~ /(NY)/ ) {
    say $capture;
}

顺便说一句,总是使用use strict; use warnings qw( all );

上述计划还需要use feature qw( say );

© www.soinside.com 2019 - 2024. All rights reserved.