1. Recursion and Callbacks(dir_walk)

ちょっと復習。。。
この章では、再帰的な処理中に何かにぶつかったときにある処理をさせたい、と言うことを効率的にやる方法が書かれている。
一例はこの通り。

#!/usr/bin/env perl 

use strict;
use warnings;

sub dir_walk {
    my ($top, $code) = @_;
    my $DIR;

    $code->($top);

    if (-d $top) {
	my $file;
	unless (opendir $DIR, $top) {
	    warn "Could't open directory $top: $!; skippin.\n";
	    return;
	}
	while ($file = readdir $DIR) {
	    next if ($file eq '.' || $file eq '..');
	    dir_walk("$top/$file", $code);
	}
    }
}

my $dir = "/Users/tomo/Program";
dir_walk($dir, sub { print $_[0] . "\n"});
dir_walk($dir, sub { printf "%6d  %s\n", -s $_[0], $_[0] });