Monday, August 27, 2007

File Input/Output :: File Tests

  • For further fool-proof file Error Handling and the Misc. you can pass file tests to filehandles. To test the existence of a file you can do this for example:
      $filename = "hooray.index";
    if (-e $filename) {
    open(outf, ">>hooray.index");
    } else {
    open(outf, ">>hooray-hooray.index");
    }
  • There are many other file tests: -T tests for ASCII file, -B tests for a Binary file, -d tests for a directory, -l tests for a symlink. There are tons of other tests listed on Schwartz pgs. 112-113. You can run these tests of filehandles also.
  • Perl provides a way to query information about a particular file also:
      ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime,
    $ctime, $blksize, $blocks) = stat ($filename);
    The stat function provides all these fields about the particular file $filename. Refer to Wall Pgs. 800-801 for more information about stat. You can also get information about a file using the File::stat package:
      use File::stat;
    $sb = stat($filename);
    print "$sb->size\n";
    This would print the size of the file. More on File::stat in the Larry Wall book.

No comments: