No modules? Tsk tsk. Well, if you insist, then you should
read Directory Recursion. But, should you come to your senses,
i recommend File::Find -
perl -MFile::Find -le 'find sub{$x+=-s$_},shift;print$x' some_dir
Update: oops, forgot about them pesky dots - actually, you
need only check for . with File::Find:
perl -MFile::Find -le 'find sub{return if/^\.$/;$x+=-s$_},shift;print$
+x' some_dir
Now, why no modules?
jeffa
perl -le 'sub r{$r=shift;print(chop$r),r($r)if$r}r("noisrucer")'
| [reply] [d/l] [select] |
sub dir_size
{
my $dir = shift;
local *DIR;
my $size = 0;
my $file;
opendir(DIR, $dir) or die "Failed to open $dir: $!\n";
while ($file = readdir(DIR))
{
# Skip . and ..
if ($file !~ /^\.\.?$/)
{
if (-d "$dir/$file")
{
$size += dir_size("$dir/$file");
}
else
{
$size += -s "$dir/$file";
}
}
}
closedir(DIR);
return $size;
}
my $size = dir_size("/foo/bar");
| [reply] [d/l] |
$ cd /foo/bar ; ln -s . snaretrap
Now watch that code run forever.
Check for symlinks before you recurse. Of course, if several files are hardlinked to each other below /foo/bar/, they will be counted multiple times, which may or may not be desired - likely not. stat files and check if you've seen that combination of device and inode number before. Etc etc etc..
It's only an innocent looking problem.
Makeshifts last the longest.
| [reply] |
You should get a warning that readdir might return "false" values, e.g. a file named "0".
while(defined(my $file = readir DIR)){
Anyway it's better to use File::Find.
| [reply] [d/l] |
Ok Im tryint to do this with No Modules :
Is this homework or do you like bondage SM? Just use File::Find. It's in the core distribution, so available everywhere.
Say a I have a direcotry that I want to get the size of all the files in it,
but there is directories inside that directory that have files and more direcotries in side sub-direcotries
Just use File::Find or, if you really do not want to, at least copy its source - this wheel has already been invented.
- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.
| [reply] |
Are we to belive that only you can reinvent wheels, Juerd? Or perhaps only you are able to judge which wheels are in need of reinventing?:) rdfield
| [reply] |
Are we to belive that only you can reinvent wheels, Juerd?
No, everyone can.
Or perhaps only you are able to judge which wheels are in need of reinventing?
No, many people are - as you can see, I'm not the only one who advises using File::Find.
- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.
| [reply] |