我的perl中有两个数组,我想要grep,一个数组来自其他数组,我的perl代码如下所示。
#!/usr/bin/perl
open (han5, "idstatus.txt");
open (han4, "routename.txt");
@array3 = <han4>;
@array4 = <han5>;
foreach (@array3) {
@out = grep(/$_/, @array4);
print @out; }文件routename.txt
strvtran
fake
globscr 文件idstatus.txt
strvtran online
strvtran online
strvtran online
globscr online
globscr online
globscr online
globscr online
globscr online
Xtech dead
Xtech dead
fake online
fake online
fake connecting
walkover123 online
walkover123 online现在,我希望grep、、globscr、来自idstatus.txt和output的元素应该如下所示:
globscr online
globscr online
globscr online
globscr online
globscr online我不想使用任何系统命令。请帮帮我
发布于 2014-01-13 06:43:37
您没有移除换行符,所以您的匹配在它所要寻找的内容中包含了一个换行符。
您还需要使for循环使用不同的变量,因为在grep内部,$_将只引用当前正在检查的grep列表中的元素。
尝试:
chomp(@array3 = <han4>);
@array4 = <han5>;
foreach my $routename (@array3) {
@out = grep(/$routename/, @array4);
print @out;
}这将产生以下结果:
strvtran online
strvtran online
strvtran online
fake online
fake online
fake connecting
globscr online
globscr online
globscr online
globscr online
globscr online 我不知道您想从idstatus.txt获得grep globscr是什么意思;那么routename.txt扮演什么角色呢?
发布于 2014-01-13 07:36:23
与其使用grepping每一行,不如构建一个regex,该正则表达式包含路径名作为替换:
use strict;
use warnings;
use autodie;
open my $rnameFH, '<', 'routename.txt';
chomp( my @routename = <$rnameFH> );
close $rnameFH;
my $names = '(?:' . ( join '|', map { "\Q$_\E" } @routename ) . ')';
my $regex = qr /^$names/;
open my $idFH, '<', 'idstatus.txt';
while(<$idFH>){
print if /$regex/;
}
close $idFH;对数据集的输出:
strvtran online
strvtran online
strvtran online
globscr online
globscr online
globscr online
globscr online
globscr online
fake online
fake online
fake connecting该脚本创建一个OR类型的regex,方法是使用“join”对路由名进行join(打印$names以查看此)。map只引用名称中的任何元字符,例如.*^等,因为这些都会影响匹配。
希望这能有所帮助!
https://stackoverflow.com/questions/21084726
复制相似问题