On 21/08/2011 13:21, Rob Dixon wrote:

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__

I'm sorry - that wasn't the version I tested! Here is the correct working program. The second program I posted works fine.

Rob

#!/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.

my $fp;
open $fp, "<", "data.txt" or die "Cant open data.txt for input: $!";
my @buffer = <$fp>;

open $fp, ">", "data.txt" or die "Cant open data.txt for output: $!";
my $replaced;

foreach my $line (@buffer) {
  if (not $replaced) {
    $replaced++ if $line =~ s/Dood/Dude/;
  }
  print $fp $line;
}
__END__

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to