I am at my wit's end, so please tell me where I am being stupid. Given a directory of files, I am trying to create the following multi-level hash.
my %o = ( $yyyy => {$mm => {$dd => ['file_1'..'file_n']}} );
Here is my code for doing so
use strict; use File::Find; use Fcntl; # to get 'em constants use MLDBM qw(DB_File Storable); our $dir = '/home/punkish/stuff'; our $db = '/home/punkish/data/files_by_dates.bdb'; our %o; createDatesDb(); sub createDatesDb { # delete existing db, and create a new one unlink "$db"; tie %o, 'MLDBM', "$db", O_CREAT|O_RDWR, 0640 or die $! +; find(\&_buildDatesDb, ("$dir") ); untie %o; } sub _buildDatesDb { if (-f $_) { my @t = localtime( (stat("$_"))[9] ); my $yyyy = $t[5] + 1900; my $mm = sprintf("%02d", $t[4] + 1); my $dd = sprintf("%02d", $t[3]); if (exists $o{$yyyy}) { if (exists $o{$yyyy}->{$mm}) { # year, month, and day exist, so push the file # into the day's array if (exists $o{$yyyy}->{$mm}->{$dd}) { my $aref = $o{$yyyy}->{$mm}->{$dd}; push(@$aref, $_); } # year exists, and month exists, but day doesn't yet exist, # so add it and all other info else { $o{$yyyy}{$mm}{$dd} = [$_]; } } # year exists, but month doesn't yet exist, # so add it and all other info else { $o{$yyyy}{$mm} = {$dd => [$_]}; } } # year doesn't yet exist, so add it and all other info else { $o{$yyyy} = {$mm => {$dd => [$_]}}; } } }
Pretty, simple. Except, it doesn't work, and I can't figure out why. If I Dumper \%o, I get the entire structure only one level deep. That is, I get all the years, but for each year, I get only one month, and for each month, I get only one day, and for each day, I get only one file in the array.
Here is the kicker. If I don't tie the hash, that is, I comment the unlink ..; tie ..; untie ..; lines in createDatesDb then Dumper \%o the untied hash, it shows up just the way I want it... that is, the hash is populated with all the files. Obviously, my logic is working, but the tie-ing is not.
What am I overlooking?
In reply to tie oddity by punkish
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |