#!/usr/bin/perl -w
use strict;
my $input;
my $output;
my $search;
my $replace;
print "enter an input file name:\n";
$input = <STDIN>;
chomp($input);
print "enter an output file name:\n";
$output = <STDIN>;
chomp($output);
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 ($!)";
while (<INFILE>) {
s/$search/$replace/g;
print OUTFILE $_;
}
You have opened OUTFILE (OUTFILE, "<$output" ) in read mode . To
write to this file you need to open in write mode (">$output").
Sunita
#!/usr/bin/perl -w
use strict;
--
To unsubscribe, e-mail: beginners-...@perl.org
For additional commands, e-mail: beginne...@perl.org
http://learn.perl.org/
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