On 21/08/2011 12:33, Ron Weidner wrote: > > Recently, I was asked to find the first occurrence of a word in a > text file and replace it with an alternate word. This was my > solution. As a new Perl programmer, I feel like this solution was too > C like and not enough Perl like. So, my question is what would have > been the Perl like solution to this problem? > > In this example there is little risk of running out of memory > reading the file. But had this been a production environment or an > unknown file size, I would have had to consider that. > > > #!/usr/bin/perl > use strict; > use warnings; > > #program finds the first occurrence of the word Dood and > #replaces it with the word Dude in the file data.txt. > > open FP, "+<", "data.txt" || die "Cant open data.txt " . $!; > > my @buffer =<FP>; > seek FP,0,0; > my $do_replace = 1; #used to control replacing in multiline files. > my $line; > my $data; > foreach $data (@buffer) > { > if ($do_replace == 1) > { > $line = $data; > $data =~ s/Dood/Dude/; > if ($line ne $data) > { > $do_replace = 0; #we did a substitution so do no more. > } > } > print FP $data; > } > close FP; > > #Test data > #Dude! Where's my car? > #Dood! Where's my car? > #Dood! Where's my car?
Hey Ronald Here is a program like yours, that reads the entire file into memory and then outputs the altered version. #!/usr/bin/perl use strict; use warnings; #program finds the first occurrence of the word Dood and #replaces it with the word Dude in the file data.txt. open my $fp, "<", "data.txt" or die "Cant open data.txt for input: $!"; my @buffer = <$fp>; open my $fp, ">", "data.txt" or die "Cant open data.txt for output: $!"; my $replaced; foreach my $line (@buffer) { unless ($replaced) { $replaced++ if $line =~ s/Dood/Dude/; } } __END__ But if you may be working with large files and have to be careful with memory, it is best to process the input file one line at a time. There are special built-in ways of doing this sort of thing, but it is best for now to write something that is clear and straightforward. Something like this perhaps. #!/usr/bin/perl use strict; use warnings; #program finds the first occurrence of the word Dood and #replaces it with the word Dude in the file data.txt. rename 'data.txt', 'data.old' or die "Rename of input file failed: $!"; open my $in, '<', 'data.old' or die "Failed to open input file: $!"; open my $out, '>', 'data.txt' or die "Failed to open output file: $!"; my $replaced; while (my $line = <$in>) { unless ($replaced) { $replaced++ if $line =~ s/Dood/Dude/; } print $out $line; } __END__ I hope this helps, Rob -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/