Tuesday, September 25, 2012

Getting Size of a directory

# Function Name    : getDirSize
# Input                    : File or Folder name
# Output                : Size in bytes
# Description            : This subroutine will return the size in bytes for given folder or file
#
sub getDirSize($)
{
    my $dir = shift;
    my $size = 0;            
    find(sub { $size += -s if -f $_ }, "$dir");
    return $size;
}

# Function Name    : format_size
# Input                    : 1. Size in bytes and 2. digits after decimal. Default is zero
# Output                : Size in KB or MB or GB
# Description            : This subroutine will return the size in highest possible unit
#
sub format_size($$)
{
    my $size = shift;
    my $decimal = shift;

    if ((not defined $decimal) || (&trim($decimal) == ""))
    {
        $decimal = 0;
    }

    return "${size}bytes" if ($size < 1024) ;
    $size = sprintf("%.${decimal}f", $size/1024);
    return "${size}KB" if ($size < 1024)  ;
    $size = sprintf("%.${decimal}f", $size/1024);
    return "${size}MB" if ($size < 1024)  ;
    $size = sprintf("%.${decimal}f", $size/1024);
    return "${size}GB";
}

No comments:

Post a Comment