in reply to Re: Get the Total Size & Total Files in a Directory
in thread Get the Total Size & Total Files in a Directory

The advice "don't roll your own solution - use a module" applies to system utilities as well. Perhaps even more so. Your solution is wrong, as it doesn't take links into account.
#!/usr/bin/perl use strict; use warnings; use File::Spec::Functions qw( no_upwards ); use File::Find; use List::Util qw( sum ); my $dir = "foo/bar"; # # Clear directory if it exists. # system "rm", "-rf", $dir and die; # # Create new directory # system "mkdir", "-p", $dir and die; # # Create big file. # system "dd", "if=/dev/zero", "of=$dir/big1", "bs=8096", "count=1024" a +nd die; # # Create a link # link "$dir/big1", "$dir/big2" or die "link: $!"; # # Calculate size by Aristotle method: # my ( $num, $size1 ); find( { preprocess => sub { my @l = no_upwards( @_ ); $num += @l; $size1 += sum map -s, @l; return @_; }, wanted => sub {}, }, $dir ); # # Calculate size by not rolling your own: # my ($size2) = `du -b $dir` =~ /\d+/g; printf "System thinks size equals %d kbytes, Aristotle thinks %d kbyte +s\n", $size2 / 1024, $size1 / 1024; __END__ 1024+0 records in 1024+0 records out System thinks size equals 8130 kbytes, Aristotle thinks 16192 kbytes
And the existance of hardlinks isn't the only thing your solution gets wrong.

Replies are listed 'Best First'.
Re^3: Get the Total Size & Total Files in a Directory
by gellyfish (Monsignor) on Jan 12, 2005 at 15:43 UTC

    Er, the only problem here is that by the OPs stating he has files in the directory c:\temp\ we can infer it is a windows machine: a) it is unlikely that the system utilities you suggest are available on windows. b) there aren't hard links on windows so the problem wouldn't arise in the first place.

    /J\

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re^3: Get the Total Size & Total Files in a Directory
by Aristotle (Chancellor) on Jan 12, 2005 at 22:39 UTC
    --- t.pl.orig 2005-01-12 23:49:42.000000000 +0100 +++ t.pl 2005-01-12 23:53:06.000000000 +0100 @@ -4,0 +5,6 @@ +sub blocksize { + my $fname = @_ ? $_[ 0 ] : $_; + my @s = ( stat $fname )[ 11, 12 ]; + return $s[ 0 ] * $s[ 1 ]; +} + @@ -8 +14 @@ - my @l = no_upwards( @_ ); + my @l = grep -f || -d, no_upwards( @_ ); @@ -10 +16 @@ - $size += sum map -s, @l; + $size += sum map blocksize(), @l;

    Makeshifts last the longest.