llobrin has asked for the wisdom of the Perl Monks concerning the following question:

i'm wondering if *.tar.gz is classified as file coz i'm trying to get the file size of that kind of file. can you help me to lighten about getting file size?

Replies are listed 'Best First'.
Re: how to get filesize
by bobf (Monsignor) on Dec 16, 2006 at 04:27 UTC

    Yes, a file with a gz extension is still a file*.

    Here is an example that shows two ways to get the size of a file: using the file test -s (see -X in perlfunc) and the function stat. Note that both of these may not be 100% portable, as per the docs.

    use strict; use warnings; my $file = 'find_my_size.tar.gz'; my $size = -s $file; print "size of $file by -s is $size\n"; my @filedata = stat $file; print "size of $file by stat is $filedata[7]\n";

    *Unless it's a directory that ends in .gz, etc

Re: how to get filesize
by SFLEX (Chaplain) on Dec 16, 2006 at 11:33 UTC
    bobf showed almost every way to get a file size.

    But this is the way I use File::Stat

    use File::Stat; my $size = (stat($filename))[7]; print "File size with \"File::Stat\" $size \n";
    all methods work well.

      If you want the size of the things inside the file, then you'd probably need to use tar. They say /bin/tar is faster, but Archive::Tar is more portable...
      use strict; use warnings; use Archive::Tar; die "no file?" unless $ARGV[0] and -f $ARGV[0]; my $size = 0; my @arch = Archive::Tar->new($ARGV[0])->list_files([qw(size)]); $size += $_->{size} for @arch; eval "use Number::Format"; if( $@ ) { print "$size\n"; } else { my $fmt = new Number::Format; print "", $fmt->format_bytes( $size, 1), "\n"; }

      -Paul

        Archive::Tar is more portable...

        GNU tar (compiled C) is freely available for all platforms that run Perl, can't be beat for speed, and will always work regardless of how big the tar file happens to be.

        (The only OS-dependent limitation, last time I checked, is that on mswin, you can't do things like "tar czf file.tar.gz source/" or "tar xzf file.tar.gz" or "tar tzvf file.tar.gz", to handle gzip compression directly -- you have to do "gzip" or "gunzip" as a separate step.)

        Meanwhile, Archive::Tar tries to accommodate both uncompressed and compressed tar files by always loading the full, uncompressed tar file contents into memory, which means that it won't handle really large tar files. (In this sense, it's "less portable".)

      hmmm... if you're using File::stat (not File::Stat! Odd, but it seems like someone uploaded a File::Stat to CPAN :p ), then you can use it like this:
      use File::stat; printf qq(File size with "File::stat" is %s\n), stat($filename)->size;
      And unlike File::Stat, File::stat is a CORE module...