URL: https://www.opennet.me/cgi-bin/openforum/vsluhboard.cgi
Форум: vsluhforumID9
Нить номер: 5876
[ Назад ]

Исходное сообщение
"отлличие m// от m/b/"

Отправлено alexvs , 06-Ноя-06 00:30 
Кто-то может объяснить на пальцах отличие m/[b]/ от m/b/. Почему по разному себя ведут следующие програмки?

perl -e 'my $str="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; if($str=~/a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b/) {print "Ok\n";};'

и

perl -e 'my $str="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; if($str=~/a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*[b]/) {print "Ok\n";};'


Содержание

Сообщения в этом обсуждении
"отлличие m// от m/b/"
Отправлено ihor , 07-Ноя-06 13:26 
Вот кусок из "perlretut":
============================
The answer lies in the optimizations the REx engine makes. In the first case, all the engine sees are plain old characters. It's smart enough to realize that the string '...' doesn't occur in our target string before actually running the pattern through. But in the second case, we've tricked it into thinking that our pattern is more complicated than it is. It takes a look, sees our character class, and decides that it will have to actually run the pattern to determine whether or not it matches, and in the process of running it hits the print statement before it discovers that we don't have a match.
=============================

Можно использовать "use re 'debug';", чтобы увидеть, что происходит. Напр.:
=====================================
use re 'debug';

$num = 15;

$re_str = 'a*' x $num;
$str='a' x $num;

$re_big = qr/$re_str/;
$re_1 = qr/(?:$re_big)b/;
$re_2 = qr/(?:$re_big)[b]/;


if ($str =~ /$re_1/) {
  print("'re_1' matches\n");
} else {
  print("'re_1' doesn't match\n");
}

if ($str =~ /$re_2/) {
  print("'re_2' matches\n");
} else {
  print("re_2 doesn't match\n");
}