Section 9.8. Displaying Recursively Defined Data


9.8. Displaying Recursively Defined Data

The Dumper routine of Data::Dumper displays the output nicely, but what if we don't like the format being used? We can write a routine to display the data. Again, for recursively defined data, a recursive subroutine is usually the key.

To dump the data, we need to know the name of the directory at the top of the tree, because that's not stored within the structure:

 sub dump_data_for_path {             my $path = shift;             my $data = shift;             if (not defined $data) { # plain file                     print "$path\n";                     return;                     }             ...             } 

For a plain file, dump the pathname; for a directory, $data is a hash reference. Let's walk through the keys and dump the values:

 sub dump_data_for_path {         my $path = shift;         my $data = shift;         if (not defined $data) { # plain file                 print "$path\n";                 return;         }         my %directory = %$data;         for (sort keys %directory) {                 dump_data_for_path("$path/$_", $directory{$_});         } } 

For each element of the directory, we pass a path consisting of the incoming path followed by the current directory entry, and the data pointer is either undef for a file or a subdirectory hash reference for another directory. We can see the results by running:

 dump_data_for_path('.', data_for_path('.')); 

Again, this is more interesting in a directory that has subdirectories, but the output should be similar to:

 find . -print 

from the shell prompt.




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net