Skip to content

Instantly share code, notes, and snippets.

@jreisinger
Last active February 5, 2016 08:08
Show Gist options
  • Save jreisinger/2b35034660278d142f40 to your computer and use it in GitHub Desktop.
Save jreisinger/2b35034660278d142f40 to your computer and use it in GitHub Desktop.
Intermediate Perl (Alpaca Book), exercise 10.4
#/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