Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding evaluations in Perl regex

Tags:

regex

perl

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;

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

like image 336
Zach H Avatar asked Jul 14 '10 22:07

Zach H


1 Answers

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>

Output:

<textarea rows="1" bar="baz">howdy</textarea>
like image 58
Greg Bacon Avatar answered Oct 21 '22 10:10

Greg Bacon