Skip to content

Instantly share code, notes, and snippets.

@uasi
Created July 14, 2010 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uasi/475696 to your computer and use it in GitHub Desktop.
Save uasi/475696 to your computer and use it in GitHub Desktop.
use v6;
role Finalizable[Callable $finalizer] {
method finalize() {
$finalizer();
}
}
multi sub infix:<do>(Finalizable $finalizable, Callable $callable) {
# XXX should call $callable in caller's context
$callable($finalizable);
# RAKUDO: LEAVE is nyi
#LEAVE { $finalizable.finalize }
$finalizable.finalize;
}
sub my_chdir($dir) {
my $prev = cwd;
chdir $dir;
$dir does Finalizable[{ chdir $prev }];
}
sub my_open($file, *%mode) {
my $fh = open $file, |%mode;
$fh does Finalizable[{ $fh.close }];
}
my_chdir('~/tmp') do {
say cwd;
my_open('greeting.txt', :w) do -> $file {
$file.say('hello');
}
}
say cwd;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment