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. |