File Processing

Writing To Files

In this lesson the student will learn to:
  1. Write to files.
  2. Know how to append to a file or to overwrite a file.
By the end of this lesson the student will be able to:

	Write a short Perl script which saves
	information to a file.


WRITING TO FILES:

The following example will take each line from gern.xml that contains the pattern "company" and print it to a file called output.txt.

#!/usr/bin/perl -w open (FILE, "gern.xml") || die; @ray = <FILE>; open (FILE2, ">output.txt") || die; foreach $line (@ray){ if( $line =~ /company/){ print FILE2 $line; } } exit;



ADDING OUTPUT TO FILE:

The following script will add lines of output to a file.

#!/usr/bin/perl -w open (FILE, ">>output.txt") || die; while(1){ print "INPUT: "; $line = <STDIN>; chomp($line); if($line eq "q"){ last; } print FILE "$line\n"; } exit;
What's the difference between these two lines?
open (FILE, ">output.txt") || die; open (FILE, ">>output.txt") || die;
There is just one character added to the second line. It has >> instead of just >. The second line appends (or adds to a file). The first line over-writes the file which means that any thing that was in the file before running the script will be lost after the script is run.


FILE TEST OPERATORS -b Is name block device? -c Is name a character device? -d Is name a directory? -e Does name exist? -f Is name an ordinary file? -l Is name a symbolic link? -o Is named owned by user? -r Is name a readable file? -s Is name a non-empty file? -w Is name a writable file? -x Is name an executable file? -z Is name an empty file? -A How long since name accessed? -M How long since name modified? -T Is name a text file?


A PROGRAM THAT PRINTS THE SIZE OF A FILE IN BYTES:
#!/usr/bin/perl -w print ("ENTER FILE NAME: "); $fn = <STDIN>; chomp($fn); if(!(-e $fn)){ print ("File $fn does not exist.\n"); } else { $size = -s $fn; print ("File $fn contains $size bytes.\n"); }



ECHOES CONTENTS OF ONE OR MORE FILES:
#!/usr/bin/perl -w while($input = <>){ print $input; } exit; TO RUN TYPE: test.pl file1.txt file2.txt



PROGRAM TO CREATE RANDOM DNA SEQUENCE AND SAVE TO FILE:
#!/usr/bin/perl -w my @DNA = ("A", "G", "T", "C"); srand(time); unless(open(OUTFILE, ">DNAseq.txt")){ die("Cannot open output file\n"); } foreach my $n (0..240){ my $i = int rand(4); print OUTFILE "$DNA[$i]"; if( ($n+1)%40 == 0) { print OUTFILE"\n"; } } close(OUTFILE); exit;



ASSIGNMENT:
Write the following two short scripts:
  1. LINE COUNT: Write a script that prompts the user for a file name and reports, if the file exists, how many lines it contains.
  2. RANDOM DNA: Write a script which generates a file that contains a DNA sequence that is 40 lines long with lines which contain 60 nucleotides each.