在 Perl 正则表达式中嵌入评估 [英] Embedding evaluations in Perl regex

查看:45
本文介绍了在 Perl 正则表达式中嵌入评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写一个快速的 perl 脚本来清理一些 HTML 代码并通过 html -> pdf 程序运行它.我想丢失尽可能少的信息,所以我想扩展我的 textareas 以适应其中当前的所有文本.这意味着,在我的情况下,根据文本框中字符串的值将行数设置为计算值.

So i'm writing a quick perl script that cleans up some HTML code and runs it through a html -> pdf program. I want to lose as little information as possible, so I'd like to extend my textareas to fit all the text that is currently in them. This means, in my case, setting the number of rows to a calculated value based on the value of the string inside the textbox.

这是我目前使用的正则表达式

This is currently the regex i'm using

$file=~s/<textarea rows="(.+?)"(.*?)>(.*?)<\/textarea>/<textarea rows="(?{ length($3)/80 })"$2>$3<\/textarea>/gis;

不幸的是,Perl 似乎没有意识到我被告知在搜索和替换正则表达式中嵌入 Perl 代码的语法有没有 Perl 爱好者愿意告诉我我做错了什么?问候,扎克

Unfortunately Perl doesn't seem to be recognizing what I was told was the syntax for embedding Perl code inside search-and-replace regexs Are there any Perl junkies out there willing to tell me what I'm doing wrong? Regards, Zach

推荐答案

(?{...}) 模式是在匹配端执行代码的实验性功能,但您想要在替换端执行代码.使用 /e 正则表达式开关:

The (?{...}) pattern is an experimental feature for executing code on the match side, but you want to execute code on the replacement side. Use the /e regular-expression switch for that:

#! /usr/bin/perl

use warnings;
use strict;

use POSIX qw/ ceil /;

while (<DATA>) {
  s[<textarea rows="(.+?)"(.*?)>(.*?)</textarea>] {
    my $rows = ceil(length($3) / 80);
    qq[<textarea rows="$rows"$2>$3</textarea>];
  }egis;
  print;
}

__DATA__
<textarea rows="123" bar="baz">howdy</textarea>

输出:

<textarea rows="1" bar="baz">howdy</textarea>

这篇关于在 Perl 正则表达式中嵌入评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆