Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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
Arrays 在Perl数组中从grep声明变量_Arrays_Perl_Grep - Fatal编程技术网

Arrays 在Perl数组中从grep声明变量

Arrays 在Perl数组中从grep声明变量,arrays,perl,grep,Arrays,Perl,Grep,我正在制作一个从推文中提取url的脚本。在运行脚本并将其放入数组时,它输出了大约30个URL,其中只有一个是正确的。因此,我使用grep从数组中获取我想要的url的第一部分,并获得“find it”输出 my $tco = "http://t.co"; if (grep /$tco/, @links) { print "found it\n"; } 我想知道我是否可以从开始的那一行开始,把那一行变成一个变量,例如: $extracted_url = 'what I found in

我正在制作一个从推文中提取url的脚本。在运行脚本并将其放入数组时,它输出了大约30个URL,其中只有一个是正确的。因此,我使用grep从数组中获取我想要的url的第一部分,并获得“find it”输出

my $tco = "http://t.co";

if (grep /$tco/, @links) {
    print "found it\n";
}
我想知道我是否可以从开始的那一行开始,把那一行变成一个变量,例如:

$extracted_url = 'what I found in the array'
我该怎么做呢?提前谢谢你!,布雷特

试试这个:

my @found = (grep /\Q$tco/, @links);
for my $url (@found) {
    print "found $url\n";
}

谢谢,它将它们(有两个)打印到了控制台上。我如何将控制台上的url转换成变量?我会做一些类似$newvariable=my@found=(grep/$tco/,@links)的事情吗;如果(@found){for my$url(@found){print“found$url\n”;}}}则打印仅用于演示正在填充变量。具体来说,它们是
$found[0]
$found[1]
$newvariable
没有意义,因为它是一个变量,有两个URL。但是,如果愿意,可以在tangent的代码中将
$url
替换为
$newvariable
。请注意,由于要查找常量字符串,因此需要转义正则表达式中的特殊字符:
grep/\Q$tco/
。否则,
将匹配任何字符,并且您的正则表达式将匹配,例如
http://tacobell.com
。您也在寻找
http://t.co
每个链接中的任意位置;如果您打算只查找以该模式开头的链接,则需要
grep/^\Q$tco/