On Thu, 2008-10-09 at 19:31 -0400, David wrote:
> However, when I insert some code to write to a file it fails an odd death:
> 
> #!/usr/bin/perl -w
> use strict;

use warnings;
# This is preferred over the -w in the shebang line
# use diagnostics;
# This may replace warnings and gives a long explanation

> my $answer;
> open(WRITE,"+>/Users/dave/Documents/Programming/Perl/081008mathtables/add.txt")

open WRITE, '+>', 
'/Users/dave/Documents/Programming/Perl/081008mathtables/add.txt' or die 
"cannot open file: $!";
# You forgot the ; at the end
# You should always test an open to make sure it has worked
# The three-argument open is preferred over the two-argument one
# +> means open to write and read back later
# since your program is not reading the file, you should use just >
# See `perldoc -f open` for details

> 
> for ($a = 1; $a <= 100; $a++)

# You shouldn't use $a; sort uses it and may have collisions
# See `perldoc -f sort` for details

> {
>      for ($b = 1; $b <= 100; $b++)

# You shouldn't use $b; sort uses it and may have collisions

>       {
>       $answer = ($a-$b);
>               print WRITE "$a - $b\t$answer\n";

print WRITE "$a - $b\t$answer\n" or die "cannot print to file: $!";
# You should always test printing to file

> 
>       }
> }
> 
> close(WRITE);

close WRITE or die "cannot close file: $!";
# You should always test a close on a write
# When the program is printing it is printing to a buffer
# that only gets written to file when the buffer is full
# or the file is closed.  So a close may cause a write to disk.
# $! in a string context is the English (en_US) error message


-- 
Just my 0.00000002 million dollars worth,
  Shawn

Linux is obsolete.
-- Andrew Tanenbaum


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to