Page 1 of 1

Simple perl substition

Posted: Mon Jul 22, 2002 8:28 am
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

Re: Simple perl substition

Posted: Mon Jul 22, 2002 3:11 pm
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.



Posted: Mon Jul 22, 2002 3:16 pm
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;