Last active
February 5, 2016 08:08
-
-
Save jreisinger/2b35034660278d142f40 to your computer and use it in GitHub Desktop.
Intermediate Perl (Alpaca Book), exercise 10.4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#/usr/bin/perl | |
use strict; | |
use warnings; | |
use 5.010; | |
my $path = shift // '.'; | |
my $data = data_for_path($path); | |
#use Data::Dumper; | |
#print Dumper \$data; | |
dump_data_for_path( $path, $data ); | |
sub data_for_path { | |
my $path = shift; | |
if ( -f $path or -l $path ) { | |
return undef; | |
} | |
if ( -d $path ) { | |
opendir PATH, $path or die $!; | |
my @names = readdir PATH; | |
close PATH; | |
my %directory; | |
foreach my $name (@names) { | |
next if $name eq '.' or $name eq '..'; | |
$directory{$name} = data_for_path("$path/$name"); | |
} | |
return \%directory; | |
} | |
warn "$path of neither a file nor a directory\n"; | |
return undef; | |
} | |
sub dump_data_for_path { | |
my $path = shift; | |
my $data = shift; | |
my $level = shift // 0; | |
print ' ' x $level, $path; | |
if ( not defined $data ) { # plain file | |
print "\n"; | |
return; | |
} | |
if ( keys %$data ) { | |
print ", with contents:\n"; | |
foreach ( sort keys %$data ) { | |
dump_data_for_path( "$path/$_", $data->{$_}, $level + 1 ); | |
} | |
} else { | |
print ", an empty directory\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment