First ... Back ... Next ... Last ... (Notes home)

Files: Opening, Reading, Closing and Errors

Getting a handle on files

  • File handles are variables, but they don't require a special symbol (like $)
  • File handles are created + assigned by opening a file
  • Opened files should be specified for read, write+truncate, write+append, or read+write
  • man perlfunc has an extensive reference section on the open function. man perlopentut for a detailed tutorial on opening files
  • There are many options for opening and reading/writing files. These include:
    • Accessing fixed-length records or database (see tie)
    • Reading + writing from Unix pipes
    • Specifying binary files, Unicode files, or other "types"
    • Treating STDIN and STDOUT as files
  • Basic syntax example:
    #!/usr/bin/perl -w
    use strict;
    
    my $infile="file1.txt";  # input filename
    
    # Open; assign filehandle; exit on error:
    open (IN, "<$infile") or die "Open of $infile failed: $!";
    
    # Loop: read lines from the file
    while (<IN>) {
      print $_;              # Each input line is assigned to $_
    }
    
    # Clean up and exit:
    close(IN);
    exit;
    

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby