Skip to content

Instantly share code, notes, and snippets.

@langthom
Created April 15, 2017 12:09
Show Gist options
  • Save langthom/b5d0c34ee4b415b104893b9e54bf118c to your computer and use it in GitHub Desktop.
Save langthom/b5d0c34ee4b415b104893b9e54bf118c to your computer and use it in GitHub Desktop.
# Using defer i.e. calling a function when leaving scope.
# Neat trick for cleanup of resources.
#
# Copyright of lines 5-27 to @briandfoy_perl
use v5.10.1;
use strict;
use warnings FATAL => "all";
sub defer {
my ($sub) = @_;
my $pid = $$; # process ID
return bless sub {
if ($$ == $pid) {
# Only if same process.
$sub->();
}
}, 'my_deferer_dummy_package';
}
# Destructor, activating as going out of scope.
sub my_deferer_dummy_package::DESTROY {
my ($self) = @_;
$self->();
}
# Testing:
sub out {
my ($msg) = @_;
print "\033[1;32m[PROG]\033[0m $msg\n";
}
sub upper_caser {
my $file = shift;
&out("Allocating resources");
open my $fh, '<:crlf', $file;
&out("Defining cleanup of resources");
# Define cleanup (close) at the point where
# resources are allocated (i.e. opened).
my $defered = defer sub {
&out("deferred function called!");
close $fh;
};
# Do work.
&out("Begin work.");
while (defined(my $line = <$fh>)) {
chomp $line;
say uc $line;
}
&out("End work.");
}
# Create test file.
open my $temp, '>test.txt' or die "Unable to create temporary file: $!";
print $temp <<"EOF";
Just
another
Perl
hacker
at
work
if
it
would
work.
D'oh!
EOF
close $temp;
# Call.
upper_caser "test.txt";
# Delete temporary file.
unlink "test.txt";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment