#!/usr/bin/perl # writingToFile: # This script illustrates how to write to a file in Perl. # The filename to be used is supplied as a command-line argument. # Sample usage: # writingToFile foo.txt # Cameron Hayne (macdev@hayne.net) May 2009 use strict; use warnings; die "Usage: $0 filename\n" unless scalar(@ARGV) == 1; my $filename = $ARGV[0]; # you can use whatever you want for the filehandle instead of OUTFILE open(OUTFILE, "> $filename") or die "Failed to open file '$filename' for writing: $!\n"; for (my $i = 0; $i < 10; $i++) { my $lineNum = $i + 1; print OUTFILE "This is line $lineNum\n"; } close(OUTFILE) or warn "Failed to close file '$filename': $!\n"; # Now read back the file that was written: print "Contents of the file ('$filename') that was written\n"; open(INFILE, "< $filename") or die "Failed to open file '$filename' for reading: $!\n"; while () { chomp(); # remove the end-of-line character my $line = $_; print "$line\n"; } close(INFILE) or warn "Failed to close file '$filename': $!\n";