Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何在数组上使用正则表达式?_Regex_Arrays_Perl - Fatal编程技术网

Regex 如何在数组上使用正则表达式?

Regex 如何在数组上使用正则表达式?,regex,arrays,perl,Regex,Arrays,Perl,我想在下面的数组中找到名称tank2,所以我这样做了 #!/usr/bin/perl use strict; use warnings; my @out = ("aaa\n", "pool: tank2\n", "ccc\n"); foreach my $line (@out) {$line =~ /pool: (

我想在下面的数组中找到名称
tank2
,所以我这样做了

#!/usr/bin/perl                                                                                           
use strict; use warnings;

my @out = ("aaa\n", "pool: tank2\n", "ccc\n");
foreach my $line (@out) {$line =~ /pool: (.+)/; print $1;}
得到

Use of uninitialized value $1 in print
tank2tank2
我的两个问题是

  • 由于某种原因,该名称打印了两次,并且出现了一个错误
  • 第一次找到结果/名称时,如何将其保存在变量中

请注意,您最终不会收到
\n
,因此您必须自己打印。

非常不可读的版本:)

以及您的改进版本:

#!/usr/bin/perl                                                                                           
use strict; use warnings;

my @out = ("aaa\n", "pool: tank2\n", "ccc\n");
for my $line (@out) {
    print $1 if $line =~ /pool: (.+)/; 
}
没有
$1

my $var;
    for my $line (@out){
        print $var if ($var) = ($line =~ /pool: (.+)/);
    }

不要说
{$line=~/pool:(.+)/;print$1;}
{$line=~/pool:(.+)/&&print$1;}
永远不要无条件地使用
$1
$2
,和朋友。@GregBacon我想你的意思是“永远不要有条件地使用”@Drt Nope。Sandra的代码无条件地打印
$1
的值,因此当前面的模式不匹配时,它仍会打印,这就是bug。
#!/usr/bin/perl                                                                                           
use strict; use warnings;

my @out = ("aaa\n", "pool: tank2\n", "ccc\n");
for my $line (@out) {
    print $1 if $line =~ /pool: (.+)/; 
}
my $var;
    for my $line (@out){
        print $var if ($var) = ($line =~ /pool: (.+)/);
    }