Simple perl substition

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
ozmodiar
Forum Commoner
Posts: 35
Joined: Sat Jun 01, 2002 6:29 am
Location: Dublin, Ireland

Simple perl substition

Post by ozmodiar »

Hopefully this will be easy enough to solve. I have a text file with tags such as <!--mydir-->. I need to write a script to open the file and replace all occurrences of
<!--mydir--> with a variable value $mydir.

I know this should be easy to do but when I try it, it i get some strange results.

Can anyone give me a simple substitution script

Thank you
duke9
Forum Newbie
Posts: 7
Joined: Thu May 23, 2002 4:17 pm

Re: Simple perl substition

Post by duke9 »

ozmodiar wrote:Hopefully this will be easy enough to solve. I have a text file with tags such as <!--mydir-->. I need to write a script to open the file and replace all occurrences of
<!--mydir--> with a variable value $mydir.

Can anyone give me a simple substitution script
From the subject I assume you want that in Perl.

The following snippet should do it.

Code: Select all

# read the file into memory
open F,"<$file" or die "Couldn't open file $file for reading!\n";
my @lines = <F>;
close F;
# open the file for writing
open F,">$file" or die "Couldn't open file $file for writing!\n";
foreach my $line (@lines) &#123;
        $line =~ s/<!--mydir-->/$mydir/g;
        print F $line;
&#125;;
close F;
Might have errors in it, but that would be the general idea.


gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post by gnu2php »

Something like this should work:

Code: Select all

$mydir = "/mypath/folder";
$file = "The directory is <!--mydir-->";

$file =~ s/<!--&#1111;^\-]+-->/$mydir/e;

print $file;
[Note that with the RE above, mydir can't contain any hyphens (-).]

If you meant that the value between <!-- and --> contains the variable to use (instead of $mydir), try this:

Code: Select all

$file =~ s/<!--(&#1111;^\-]+)-->/$$1/e;
Post Reply