Sure. For each path split the path into parts:
my @parts = split /\\/, $path;
Then for each part in the path starting at the 'root' (drive specifier for example) add it to the parent hash. %pTree is the parent hash for the whole tree so we start out by setting $scan to reference that:
my $scan = \%pTree;
then the 'tricky' bit adds the parts. shift @parts removes the left most part of the path. $scan->{shift @parts} ||= {} will create a new hash element if there isn't one already. In any case it returns the hash ref for the current part of the path and that becomes the new parent $scan = ... while @parts;. Taken all together the 'tricky' bit walks down the tree generating entries as required:
$scan = $scan->{shift @parts} ||= {} while @parts;
A few important tricks:
- $scan->{shift @parts} ||= {} autovivifies (creates) an entry in the hash if it doesn't exist yet.
- ||= {} only assigns a new (empty) hash if a new entry has been created (or in the nasty special case that the directory name is 0).
- assignment operators (=, ||=, +=, ...) 'return' the value assigned which is how $scan gets updated.
Note that with Perl 5.10 and later you can use //= in place of ||= and it fixes the 0 issue mentioned in item 2.
True laziness is hard work
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.