On Tue, Nov 11, 2008 at 09:52, [EMAIL PROTECTED]
<[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;
The standard way to write this is
perl -ple 's/search_string/replace_string/' input_file > output_file
you could also say
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Std;
die "usage: $0 -s search_regex -r replace_string [input file or files]\n"
unless @ARGV >= 4;
my %opts;
getopts("s:r:", \%opts);
my $regex = qr/$opts{s}/;
my $string = $opts{r};
while (my $line = <>) {
$line =~ s/$regex/$string/;
print $line;
}
--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/