mr.nick has asked for the wisdom of the Perl Monks concerning the following question:
I would like to ask my fellow brothers and sisters how best to handle this situation. I want to scan a directory of files and store them in a hash in such a way as to fascilitate printing them out via nested HTML's <ol> tags. I have since figured out a way to get the results I want during printing, not data collection, but I still would like to know how to do it this way.
The structure of the directories look something like this.
.
|
|-- subdir 1
|-+ subdir 2
| |-- subsubdir 2.1
| |-- subsubdir 2.2
|-+ subdir 3
|-+ subsubdir 3.1
|-- subsubsubdir 3.1.1
|-- subsubsubdir 3.1.2
|-- subsubsubdir 3.1.3
(your standard directory tree). The problems I'm facing are twofold.
First of all, building the hash itself. I wanted to end result to be like this:
So I thought I could code something along the lines$hash{subdir 1} $hash{subdir 2}{subsubdir 2.1} $hash{subdir 2}{subsubdir 2.2} $hash{subdir 3}{subsubdir 3.1} $hash{subdir 3}{subsubdir 3.1}{subsubsubdir 3.1.1} $hash{subdir 3}{subsubdir 3.1}{subsubsubdir 3.1.2} $hash{subdir 3}{subsubdir 3.1}{subsubsubdir 3.1.3}
where it results in something like $hash{ $parts[0] }{ $parts[1] }{ $parts[n] }=(), where { $parts[n] } would be repeated for each element of @parts. I couldn't think of a way to do this without knowing n, the index of the last element. I suppose I could do it easily enough with eval, but I try to avoid using eval as much as possible.@parts=split /\//,$dirname; %hash{ @parts } = (); ## this doesn't work, of course, ## just an example of the idea
The second problem I have is having a hash value that can either be another hash key AND contain values. Eg, "subdir 1" can contain both files and sub directories. I know the following doesn't work:
you get a Can't use string ("1") as a HASH ref while "strict refs" in use barf from strict. But that's the effect I want.$hash{foo}=1; $hash{foo}{bar}=2;
Hm. On second thought, an anonymous array might work:
In fact, that does appear to be the effect that I want... (sorry, it came to me while I was writing this). Hm. Iterating through it won't be fun, though.#!/usr/bin/perl use strict; use Data::Dumper; my %hash; $hash{foo}=[undef,1]; $hash{foo}[0]{bar}=[undef,2]; $hash{foo}[0]{bar}[0]{bink}=[undef,4]; print Dumper \%hash;
So, any thoughts on any of this? Comments about the klunky anonymous array solution?
mr.nick ...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Data structure question: Directory-in-memory ?
by stephen (Priest) on Jun 20, 2001 at 04:36 UTC | |
by mr.nick (Chaplain) on Jun 20, 2001 at 04:47 UTC | |
|
Re: Data structure question: Directory-in-memory ?
by Anonymous Monk on Jun 20, 2001 at 13:54 UTC | |
|
(tye)Re: Data structure question: Directory-in-memory ?
by tye (Sage) on Jun 20, 2001 at 17:59 UTC |