如何确定某个值是否在Perl数组中?

时间:2010-09-21 18:23:28

标签: regex arrays perl

我正在使用这个小片段来确定某个URL当前是否存储在数组中:

if( $self->{_local} eq "true" && ! grep {m|^$new_href?$|} @m_href_array ) {
    push( @m_href_array, $new_href );
    push( @href_array, $new_href );
}

它似乎工作但我的代码抛出一个错误说:

Sequence (?$...) not implemented in regex; marked by <-- HERE in m/^javascript:SearchGo(?$ <-- HERE / at C:/Perl/site/lib/ACTC.pm line 152, <> line 1.

任何人都可以解释为什么会这样吗?

5 个答案:

答案 0 :(得分:6)

在数组中搜索字符串时,您只能使用eq,而不是正则表达式:

grep { $_ eq $new_href } @m_href_array

但是,如果你真的需要使用正则表达式(例如,你正在搜索匹配数组中子字符串的字符串,你应该总是引用字符串,以便嵌入的特殊字符在你的字符串中没有不良影响:

grep { /\Q$substr\Esomething_else/ } @array

此外,如果您关心的是值是否存在,某处,您可以在找到匹配后立即短路:

use List::Util 'first';
if (first { $_ eq $new_href } @m_href_array) { ... }

use List::MoreUtils 'any';
if (any { $_ eq $new_href } @m_href_array) { ... }

如果您要进行大量搜索,或者您的数组非常长,那么您可以通过将数组转换为哈希来更快地完成该过程,因此您可以进行O(1)查找:

my %values_index;
@values_index{@array} = ();

if (exists $values_index{$element}) { ... }

答案 1 :(得分:4)

这里你不需要正则表达式。只需使用eq

grep { $_ eq $new_href } @m_href_array

使用哈希而不是数组来加快检查是个好主意:

my %allready_used_url;

if ( $self->{_local} eq "true" && ! exists $allready_used_url{ $new_href } ) {
    $allready_used_url{ $new_href } = 1; ## add url to hash
    push( @m_href_array, $new_href );
    push( @href_array, $new_href );
}

答案 2 :(得分:0)

?中的$new_href?是什么意思?假设$new_href中有一个字符串,你希望字符串的最后一个字母是可选的吗?这不是RE解析器读取它的方式。

答案 3 :(得分:0)

看起来$new_herf的值是javascript:SearchGo(,在正则表达式检查中替换时看起来像:

^javascript:SearchGo(?$

这是一个破坏的正则表达式,因为)没有匹配的(

答案 4 :(得分:0)

您使用的是网址作为模式,并且它不是有效模式。这并不是那么糟糕,因为有更好的方法来做到这一点。智能匹配使它几乎无足轻重:

 use 5.010;

 if( $new_href ~~ @urls ) { ... }
相关问题