Модераторы: korob2001, ginnie
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Расскажите про ?{} в регвырах, Для чего оно в Perl 5.8? 
:(
    Опции темы
tishaishii
Дата 18.1.2007, 20:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Создатель
***


Профиль
Группа: Завсегдатай
Сообщений: 1262
Регистрация: 14.2.2006
Где: Москва

Репутация: 4
Всего: 8



Расскажите про ?{} в регвырах, для чего оно в Perl 5.8?
Я понимаю, что там можно выполнить код Perl, но приведите пример, когда использование ?{} на что-то влияет и необходимо.
PM MAIL ICQ Skype   Вверх
nitr
Дата 18.1.2007, 21:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 2543
Регистрация: 10.2.2006
Где: Россия :)

Репутация: 37
Всего: 84



Да извинят меня модераторы за цитату, но человек похоже не знает perldoc
perldoc perlre

Цитата
(?{ code })
WARNING: This extended regular expression feature is considered highly experimental, and may be changed or deleted without notice. 

This zero-width assertion evaluates any embedded Perl code. It always succeeds, and its code is not interpolated. Currently, the rules to determine where the code ends are somewhat convoluted.

This feature can be used together with the special variable $^N to capture the results of submatches in variables without having to keep track of the number of nested parentheses. For example:
  $_ = "The brown fox jumps over the lazy dog";
  /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
  print "color = $color, animal = $animal\n";

Inside the (?{...}) block, $_ refers to the string the regular expression is matching against. You can also use pos() to know what is the current position of matching within this string.

The code is properly scoped in the following sense: If the assertion is backtracked (compare Backtracking), all changes introduced after localization are undone, so that
  $_ = 'a' x 8;
  m< 
     (?{ $cnt = 0 })                    # Initialize $cnt.
     (
       a 
       (?{
           local $cnt = $cnt + 1;       # Update $cnt, backtracking-safe.
       })
     )*  
     aaaa
     (?{ $res = $cnt })                 # On success copy to non-localized
                                        # location.
   >x;

will set $res = 4. Note that after the match, $cnt returns to the globally introduced value, because the scopes that restrict local operators are unwound.

This assertion may be used as a (?(condition)yes-pattern|no-pattern) switch. If not used in this way, the result of evaluation of code is put into the special variable $^R. This happens immediately, so $^R can be used from other (?{ code }) assertions inside the same regular expression.

The assignment to $^R above is properly localized, so the old value of $^R is restored if the assertion is backtracked; compare Backtracking.

For reasons of security, this construct is forbidden if the regular expression involves run-time interpolation of variables, unless the perilous use re 'eval' pragma has been used (see the re manpage), or the variables contain results of qr// operator (see qr/STRING/imosx in the perlop manpage).

This restriction is because of the wide-spread and remarkably convenient custom of using run-time determined strings as patterns. For example:
    $re = <>;
    chomp $re;
    $string =~ /$re/;

Before Perl knew how to execute interpolated code within a pattern, this operation was completely safe from a security point of view, although it could raise an exception from an illegal pattern. If you turn on the use re 'eval', though, it is no longer secure, so you should only do so if you are also using taint checking. Better yet, use the carefully constrained evaluation within a Safe compartment. See the perlsec manpage for details about both these mechanisms.



--------------------
PM   Вверх
tishaishii
Дата 19.1.2007, 06:13 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Создатель
***


Профиль
Группа: Завсегдатай
Сообщений: 1262
Регистрация: 14.2.2006
Где: Москва

Репутация: 4
Всего: 8



А ты не знаешь tkpod:)))
Ну а теперь своими словами.
Я посчитать и сам могу. Это работает быстрее, чем
Код

my$cnt=0;
$cnt++ while $str=~m{$re}gcx;

?
PM MAIL ICQ Skype   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Perl"
korob2001
sharq
  • В этом разделе обсуждаются общие вопросы по языку Perl
  • Если ваш вопрос относится к системному программированию, задавайте его здесь
  • Если ваш вопрос относится к CGI программированию, задавайте его здесь
  • Интерпретатор Perl можно скачать здесь ActiveState, O'REILLY, The source for Perl
  • Справочное руководство "Установка perl-модулей", можно скачать здесь


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, korob2001, sharq.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Perl: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.4964 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.