http://qs321.pair.com?node_id=1008

File Input and Output Exercises

  1. Write a program which prompts the user for the name of a file to open, and then reads in the file line by line. When it has finished reading the file it should print the lines in reverse order. (solution)
  2. Write a program which asks the user to type the name of a file to log their typing into, and then reads in lines and writes them into the named file, stopping when it has read a line consisting only a "." on a line by itself. (solution)
  3. Write a program which copies one file to another. The program should take two command line arguments, the first being the source file name and the second being the destination file name. (solution)

Replies are listed 'Best First'.
File I/O #1
by vroom (His Eminence) on Nov 19, 1999 at 02:08 UTC
    # prompt the user for the name of a source file, and # read all the lines from that file. # Then print out the lines in reverse order. print "What is the name of the source file? "; my $file = <>; chomp $file; open FILE, "< $file" or die "error reading $file - $!"; while ( <FILE> ) { push @lines, $_; } close FILE; foreach ( reverse @lines ) { print; }
File I/O #2
by vroom (His Eminence) on Nov 19, 1999 at 02:12 UTC
    # prompts the user for a filename, then logs all input lines # to that file, until a line consisting only of "." is seen. print "What is the name of the keylogging data file? "; my $file = <>; chomp $file; open LOG, "> $file" or die "error writing $file - $!"; while ( $line = <> and $line ne ".\n" ) { print LOG $line; } close LOG;
File I/O #3
by vroom (His Eminence) on Nov 19, 1999 at 02:16 UTC
    # takes two command line arguments for the source and # destination files, respectively. Then copies the contents # from the source file to the destination file. my $source = $ARGV[0]; my $dest = $ARGV[1]; unless ( $source and $dest ) { print "Source or destination file name missing\n"; } open SOURCE, "< $source" or die "error reading $source - $!"; open DEST, "> $dest" or die "error writing $dest - $!"; while ( <SOURCE> ) { print DEST $_; } close SOURCE; close DEST;