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

I have to write a script that can be used to do search and replaces on files, and must include the ability to work with tabs, carriage returns, etc etc. I've run into the problem of that I can match using \t, \n, etc etc, but for some reason when I put \n, \t in the replace part of the regular expression it does not interpet the commands and there, and just dumps a \t and a \n into my text. This is using Perl on Slackware Linux, Perl version 5.6.0. Below is the script and the file it reads the terms from.
#!/usr/bin/perl $filename = "test.txt"; $termsfile = "test.list"; open filename or die "Can't find file $filename: $!\n"; @terms = `cat test.list`; foreach (@terms) { chomp; } $count = 1; while (read filename, $buf, 16384) { @buf1[$count] = $buf; $count++; } foreach $term (@terms) { ($search, $replace, $junk) = split /\#\#SPLIT\#\#/, $term; print STDOUT $search; print STDOUT $replace; print "\n"; foreach $buf2 (@buf1) { $buf2 =~ s/$search/$replace/g; } } print STDOUT @buf1; close filename;
The file it reads the terms from looks like. .END##SPLIT##.ENDTAGHERE\t \t##SPLIT##TAGMARKHERE
The script will go through a file and convert all 'tabs' to TABMARKHERE. But it converts all .END to the exact text of .ENDTAGHERE\t. Can someone please help me figure out this problem?

Replies are listed 'Best First'.
Re: Problems with a search and replace script
by Hot Pastrami (Monk) on Mar 22, 2001 at 00:14 UTC
    Because the text is read from a file, all special characters are already escaped in the string... so "\t" is a literal "\t" rather than a tab. You could convert them to real tabs like this:
    $buf2 =~ s/\\t/\t/g;

    Hot Pastrami