You need a way to transform the directory the file is in to the appropriate top-level directory. Use the File::Basename module, then something like:
sub topdir { my($nd,$parent)=@_; my $d = $nd; # Hack; strip off trailing characters that might be directory # seperators $parent =~ s/\W$//; while ($nd ne $parent) { $d = $nd; $nd = File::Basename::dirname($d); } return $d; }
That HACK line is in case the argument is c:\temp\ instead of just c:\temp. It should really be $dir=join("",fileparse($dir));, but that doesn't work as documented on my system.

The code to use this is:

#!/usr/bin/perl -w use strict; use File::Find; use File::Basename; our $dir = $ARGV[0]; find(\&do_dir, $dir); my %hash; sub do_dir { my $size = -s ($File::Find::name) or return; my $d = topdir($File::Find::dir,$dir); if (!defined($hash{$d})) { $hash{$d} = 0; } # warn "size=$size, d=$d\n"; $hash{$d} += $size; } foreach (keys %hash) { print "DIR $_ = $hash{$_}\n"; }

In reply to Re: Directory size 1 level deep by sgifford
in thread Directory size 1 level deep by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.