Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

this is a basic, apprentice level question, but:
am processing a bunch of xhtml files to wml format and i want to find out how i can get the value of a pattern into a variable and then interpolate this variable where needed.
files i'm processing appear thus:
<img src="xhtml/img/cancel.gif" width="24" height="13" alt="Cancel" / +> <textarea type="text" value="foo" name="text_message" />&nbsp;<%bar%>& +nbsp;</p>
what i want to do, and can't, is cut  /<%bar%>/and put it into /foo/ while replacing /textarea/ with /input/
here's where i've got to:

foreach $file (@files) { $file_new = $file; open(IN, $file_new); $content = <IN>; $content =~s/xhtml/wml/g; #...do lots more swopping here... $content =~s/<h1>/<p><b>/g; # now i want to replace /textarea/ below with /input/ and also tak +e /<%bar%>/ and put it into /foo/ # trying something like this- doesn't work while ($content =~ m/\(<textarea.*?>\)/sg) { my $match = $1; $match =~ s/\n//g; print " MATCH $match\n"; if($bar=~m/<%*?%>/){ $foo =~ m/foo/; $value_of_bar = $bar; # how to get $bar into $foo? $content =~ s/$foo/$bar/g; } } # write $content to file open(OUT, ">$ARGV[1]/$file_new") || die "cannot open $ARGV[1]/$file_ne +w"; print $content; print OUT $content;
many thanks!

Replies are listed 'Best First'.
Re: extracting regex into, and interpolating, variable
by roik (Scribe) on Oct 23, 2002 at 13:57 UTC
    I think the following aproach will achieve the string replacement you are looking for though you might want to refine it. I am assuming for example that there will always be a %bar% on a line with <textarea!
    use strict; my $line = qq(<textarea type="text" value="foo" name="text_message" /> +&nbsp;<%bar%>&nbsp;</p>); my $foo = "foo"; if ($line =~ /<textarea .+<(%.+%)>/) { my $bar = $1; $line =~ s/<textarea/<input/; $line =~ s/$bar/$foo/; print $line; } exit;
      Hi, the initial post was mine, I posted anonymously by mistake.
      Thanks for the tip. The problem is that I can't guarantee the value of "foo" or indeed the attributes of "textarea", so I have to do some kind of pattern match like m/\(<textarea.*?>\)/ and then do a match on that to get the value of "value", if that makes sense.
      then, I need to insert all this into the variable that contains the whole file i.e. $content
      thanks,
      z.
        Hi, having read your post a little more carefully, I think maybe this is a bit closer to what you want. $1 holds the match after "value=".
        use strict; my $line = qq(<textarea type="text" value="foo" name="text_message" /> +&nbsp;<%bar%>&nbsp;</p>); if ($line =~ /<textarea .+ value="(.+?)".+(<%.+%>)/) { my $foo = $1; my $bar = $2; $line =~ s/<textarea/<input/; $line =~ s/$bar/$foo/; print $line; }