Jim Gibson wrote:
At 10:59 PM -0400 3/31/10, Vincent Cannavale wrote:

You should have the following at the beginning of your program so Perl will help you find the errors:

use strict;
use warnings;

#open a text file for reading, since opening for writing wipes the file
open(INFILE, "<perlfile.txt");

You should use the 3-argument version of open, use a lexical variable for the file handle, and check for success:

open( my $infile, '<', 'perlfile.txt') or die("Error opening file: $!");

#assign the file, identified by the file handle to an array, then "transform"
#the array into a scalar variable by joining each element in the array
#(a line) with a new line character
$variable = join(@variable = <INPUT>, "\n");

You have misspelled the file handle (Perl will tell use with 'use strict' in effect) and swapped the arguments to join, and there is no need for the array variable:

my $variable = join( "\n", <$infile>);

Both versions will add an extra newline to every line except for the last one. Slurp the file instead. (See `perldoc perlvar` and search for /\$INPUT_RECORD_SEPARATOR/ )

my $variable;
{
  local $/;
  $variable = <$infile>;
}


close(INFILE);

close $infile;

open(OUTFILE, ">perlfile.txt");

open my $outfile, '>', 'perlfile.txt' or die "could not open perlfile.txt for writing: $!\n";


$variable =~ s/0/zero/g ;
$variable =~ s/1/one/g ;
$variable =~ s/2/two/g ;
$variable =~ s/3/three/g ;
$variable =~ s/4/four/g ;
$variable =~ s/5/five/g ;
$variable =~ s/6/six/g ;
$variable =~ s/7/seven/g ;
$variable =~ s/8/eight/g ;
$variable =~ s/9/nine/g ;

#print the changed text back to the file and close it.
print OUTFILE "$variable";

print $outfile $variable or die "could not print to perlfile.txt: $!\n";

close(OUTFILE);

close $outfile or die "could not close for writing perlfile.txt: $!\n";


Please note that because of buffering, the last print may not happen until the file is closed.


--
Just my 0.00000002 million dollars worth,
  Shawn

Programming is as much about organization and communication
as it is about coding.

I like Perl; it's the only language where you can bless your
thingy.

Eliminate software piracy:  use only FLOSS.

--
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