in reply to Create PerlIO::via layer to append data at the end of a file
Instead of an IO layer, would a tied handle do for you? Here's an example.
use warnings; use strict; use 5.006; { package Tie::Handle::CloseAppend; sub TIEHANDLE { my($class, $string, $handle) = @_; my %obj; $obj{"handle"} = $handle; # this argument to tie is optional $obj{"string"} = $string; $obj{"open"} = defined($handle); bless \%obj, $class; } sub OPEN { my($obj, $arg, @arg) = @_; $$obj{"open"} = 1; open $$obj{"handle"}, $arg, @arg; } sub _preclose { my($obj) = @_; printf { $$obj{"handle"} } "%s", $$obj{"string"} or warn "warning: could not print closing string to Tie::Handle:: +CloseAppend handle: $!"; } sub CLOSE { my($obj) = @_; _preclose($obj); $$obj{"open"} = 0; close $$obj{"handle"}; } sub DESTROY { my($obj) = @_; if ($$obj{"open"}) { _preclose($obj); } }
sub WRITE { warn Dumper(["WRITE",@_]); 1; } sub PRINT { my($obj, @arg) = @_; print { $$obj{"handle"} } @arg; } sub PRINTF { my($obj, $arg, @arg) = @_; printf { $$obj{"handle"} } $arg, @arg; } for my $m (qw"READ READLINE GETC EOF SEEK TELL") { my $mm = $m; my $p = sub { die "error: $mm unimplemented for Tie::Handle::CloseAppend han +dle"; }; { no strict "refs"; *$m = $p; } } sub BINMODE { my($obj, $arg) = @_; binmode $$obj{"handle"}, $arg; } sub FILENO { my($obj) = @_; fileno($$obj{"handle"}); }
} use Symbol; my $APP = gensym(); # Create the lexical handle the old style way, # for open can autovivify globs but tie can't. tie *$APP, Tie::Handle::CloseAppend::, "END"; open $APP, ">-" or die "error opening"; print $APP "Lorem ipsum dolor sit amet "; # note: perl will close handle when $APP goes out of scope __END__
Update: changed line in TIEHANDLE from $obj{"open"} = 0; to $obj{"open"} = defined($handle);.
|
|---|