convenientstore has asked for the wisdom of the Perl Monks concerning the following question:

Hello, while reading Intermediate perl, I got stuck on page 97. which has this code
#!/usr/bin/perl -w use strict; use Data::Dumper; sub data_for_path { my $path = shift; if (-f $path or -l $path) { #files or symbolic links return undef; } if (-d $path) { my %directory; opendir PATH, $path or die "cannot opendir $path: $!"; my @names = readdir PATH; closedir PATH; for my $name (@names) { next if $name eq '.' or $name eq '..'; $directory{$name} = data_for_path("$path/$name"); } return \%directory; } warn "$path is neither a file nor a directory\n"; return undef; } print Dumper(data_for_path('.'));
which shows me the output of
$VAR1 = { 'perl.1' => undef, 'bin' => { 'perl.1' => undef, 'chaos.1' => undef }, 'perl.sub_sub' => undef, 'perl.sub_multi' => undef, 'chaos.1' => undef, 'perl.filehandle' => undef, 'man' => {}, 'lib' => { 'yahoo3' => { 'yahoo3' => { 'yahoo1111' => undef }, 'yahoo5' => undef }, 'yahoo2' => undef, 'yahoo' => undef }, 'perl.log' => undef, 'perl.recursive_data' => undef, 'perl.callbacks' => undef };
But I was trying to do it without datadumper to see if I can print out the structure..(possibly with references) tried couple things but does not work.. any suggestion? Problem I see is that I am not so sure what is being return from the sub routines.. and even if I know what it looks like, if sub directory has multiple subdirectories.. woudln't it make it almost impossible to build a right structure of reference?

Replies are listed 'Best First'.
Re: subroutine reference questions
by brian_d_foy (Abbot) on Sep 01, 2007 at 20:17 UTC

    You have to look on the next page. :)

    In "Displaying Recursively Defined Data" on page 98, we show you how to do it. The dump_data_for_path routine, which is also recursive. displays the data structure. The code itself is on page 99:

    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{$_}); } }
    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
      :-) thanks~
Re: subroutine reference questions
by FunkyMonk (Bishop) on Sep 01, 2007 at 18:53 UTC
    Have a look at ref. It'll tell you what kind of reference the argument is, or return an empty string if it's a scalar. For example:
    my $hashref = {}; my $arrayref = []; my $coderef = sub {}; my $scalar = ''; print "[", ref, "]\n" for $hashref, $arrayref, $coderef, $scalar;

    Outputs

    [HASH] [ARRAY] [CODE] []