On 12/04/2011 01:47, mark baumeister wrote:
Hi I am having trouble with my search and replace code in the
program below.
I can sucessfully copy the input file to the output file but
my search and replace is not working. Any hints on what I am doing
wrong?
Hello Mark.
You must tell us what is happening to indicate that your search and
replace isn't working. In the mean time here are some comments on your
code.
#!/usr/bin/perl -w
use strict;
You should 'use warnings' here instead of -w or -W on the command line.
my $input;
my $output;
my $search;
my $replace;
Once you have used 'use strict' it is best to declare variables as
closely as possible to their use. Only FORTRAN or very old C required
declaration at the start of a block.
print "enter an input file name:\n";
$input =<STDIN>;
chomp($input);
print "enter an output file name:\n";
$output =<STDIN>;
chomp($output);
OK, but omit the declaration at the top and
chomp (my $input = <STDIN>);
etc.
print "enter a search pattern:\n";
$search =<STDIN>;
chomp($search);
print "enter a replacement string:\n";
$replace =<STDIN>;
chomp($replace);
open INFILE, "<$input" or die "Can’t open $input ($!)";
open OUTFILE, "<$output" or die "Can’t open $output ($!)";
Common wisdom says that you should write
open my $infile, '<', $input or die "Can't open $input ($!)";
while (<INFILE>) {
s/$search/$replace/g;
print OUTFILE $_;
}
If you have taken my advice and used a lexical file handle then this is
while (<$infile>) {
s/$search/$replace/g;
print $outfile;
}
My best guess is that there are characters in $search that mean
something special in the context of a regular expression. You really
should have explained your problem properly, but to fix that you should
write instead
while (<$infile>) {
s/\Q$search/$replace/g;
print $outfile;
}
If this doesn't fix your problem then please ask again, but please also
try to rephrase your question properly.
HTH,
Rob
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/