in reply to Re: Case of autovivification
in thread Case of autovivification

Sorry, I wrote a bad example, my mistake. Please look at the complete code, I am trying to build hash of hashes where each folder is a key. Early I did hash of hashes where keys are full path to folder, but it wasn't pretty.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %filesystem; my $ref = $filesystem{root} ||= {}; traverse(".",""); sub traverse{ my ($folder,@path) = @_; opendir DIR,$folder; my @list = grep {!/^\.{1,2}$/} readdir DIR; # exclude . and .. closedir DIR; foreach my $entry(@list){ next if ( -l $folder."/". $entry); # skip links $ref = $$ref{$_} ||= {} for @path; if( -d $folder."/". $entry){ traverse($folder."/".$entry,@path,$entry); }else{ $$ref{$folder} = $entry; }; }; }; print Dumper(\%filesystem);

if I run it it eat all my RAM, so I think I use $ref from your example wrong

Replies are listed 'Best First'.
Re^3: Case of autovivification
by toolic (Bishop) on Oct 11, 2008 at 21:13 UTC
    It seems like you are trying to build up a deeply nested data structure which looks a lot like your directory tree. However, if all you need is a simple array of full paths to files, take a look at File::Find::Rule, which recursively traverses the filesystem.
Re^3: Case of autovivification
by ikegami (Patriarch) on Oct 11, 2008 at 18:06 UTC
    You need to decide what you want your data structure to look like before you do anything else. Right now, you're trying to store every non-directory file in directory at the same key as the directory itself.
Re^3: Case of autovivification
by ig (Vicar) on Nov 05, 2008 at 04:58 UTC

    Try running your script with some extra print statements and you can see what it is doing as it progresses. I expect the data structure it is building is not what you want and may help explain why you are using so much memory.

    You should think carefully about the line $ref = $$ref{$_} ||= {} for @path; in your subroutine.

    Also, your subroutine is recursive. It keeps changing the global variable $ref. Think about what $ref is referencing and how this changes as your program progresses.