Документация
HTML CSS PHP PERL другое

Section 9.8.  Displaying Recursively Defined Data

 
Previous
Table of Contents
Next

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.


Previous
Table of Contents
Next
© 2000- NIV