On Nov 12, 6:55 am, [EMAIL PROTECTED] (Rob Dixon) wrote: > [EMAIL PROTECTED] wrote: > > Hi I am new to this group and to Perl. > > > I am having trouble with searching and replacing a pattern in a file > > and then > > copying to a new file. I am trying to write an interactive program to > > do this > > where I input the file name for the search and replace and the file > > name > > for the modified file to be saved. > > > Here is my code. > > Can anyone offer any suggestions? > > Thanks in advance. > > > #!/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>; > > > 's/$search/$replace/g' $input >> $output; > > You need to open your input and output files, then lines from the input file, > modify them, and write them to the output file one at a time. > > HTH, > > Rob > > #!/usr/bin/perl > use strict; > use warnings; > > print "enter an input file name:\n"; > my $input = <STDIN>; > chomp ($input); > > print "enter an output file name:\n"; > my $output = <STDIN>; > chomp ($output); > > print "enter a search pattern:\n"; > my $search = <STDIN>; > chomp ($search); > > print "enter a replacement string:\n"; > my $replace = <STDIN>; > chomp ($replace); > > open my $in, '<', $input or die "Can't open '$input': $!"; > open my $out, '>', $output or die "Can't open '$output': $!"; > > while (<$in>) { > s/\Q$search/$replace/g; > print $out $_; > > > > }- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text -
Thanks a lot, Rob. That works great. I think I understand most of your suggestions but I'm not very clear in this line: print $out $_; # in the while loop below. while (<$in>) { s/\Q$search/$replace/g; print $out $_; What is the $_ variable? Is that an element of the @ARGV array? If so, is my output file saved in $_ temporarily until it is 'sent' to the $out file handle and then copied $output? Please excuse my ignorance if I am totaly off. Mark -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/