2012年1月11日 星期三

[Perl] Get Size of Files or Directories

Sample code:
use File::Find;

# Get size of entry (file or directory) in bytes.
sub entry_size {
    if (-f $_[0]) {
        -s $_[0];
    } elsif (-d $_[0]) {
        my $size = 0;
        finddepth( sub { $size += -s if -f $_ }, $_[0] );
        $size;
    }
}

Notes:
  1. File::Find module - Traverse a directory tree. Usage:
    finddepth(\&wanted, @directories);
    finddepth(\%options, @directories);
  2. File tests and their meanings
    File testMeaning
    -rFile or directory is readable by this (effective) user or group
    -wFile or directory is writable by this (effective) user or group
    -xFile or directory is executable by this (effective) user or group
    -oFile or directory is owned by this (effective) user
    -RFile or directory is readable by this real user or group
    -WFile or directory is writable by this real user or group
    -XFile or directory is executable by this real user or group
    -OFile or directory is owned by this real user
    -eFile or directory name exists
    -zFile exists and has zero size (always false for directories)
    -sFile or directory exists and has nonzero size (the value is the size in bytes)
    -fEntry is a plain file
    -dEntry is a directory
    -lEntry is a symbolic link
    -SEntry is a socket
    -pEntry is a named pipe (a “fifo”)
    -bEntry is a block-special file (like a mountable disk)
    -cEntry is a character-special file (like an I/O device)
    -uFile or directory is setuid
    -gFile or directory is setgid
    -kFile or directory has the sticky bit set
    -tThe filehandle is a TTY (as reported by the isatty() system function;
    filenames can’t be tested by this test)
    -TFile looks like a “text” file
    -BFile looks like a “binary” file
    -MModification age (measured in days)
    -AAccess age (measured in days)
    -CInode-modification age (measured in days)

  3. @_ is the list of parameters to a sub. So if you write a sub, you refer to the first parameter in it as $_[0], the second parameter as $_[1] and so on. $_ is known as the "default input and pattern matching space."

沒有留言:

張貼留言