Skip to content

Commit

Permalink
awk: now with File::Temp (#557)
Browse files Browse the repository at this point in the history
* Take a hint from bin/find program, and use File::Temp instead of manually opening TMPIN and TMPOUT
* File::Temp also handles removal of the files, so the END block gets simplified
* "perl awk -f hello.awk" still produced the same output with patch applied
  • Loading branch information
mknos committed Apr 15, 2024
1 parent acc9877 commit 669a776
Showing 1 changed file with 12 additions and 20 deletions.
32 changes: 12 additions & 20 deletions bin/awk
Expand Up @@ -17,17 +17,15 @@ License: perl

use strict;

use File::Temp qw(tempfile);

my(
$program, # the code to eval
$tmpin, # the files a2p reads
$tmpout, # the files a2p writes
@nargs, # new args for a2p
@vargs # temporary holder of variables
);

END {
no warnings qw(uninitialized);
unlink $tmpin, $tmpout; # XXX: don't check failure
close STDOUT || die "$0: can't close stdout: $!\n";
$? = 1 if $? == 255; # from die
}
Expand All @@ -46,13 +44,8 @@ usage() unless @ARGV;
open(SAVE_OUT, '>&', STDOUT) || die "can't save stdout: $!";
die unless defined fileno SAVE_OUT;

open(TMPIN, '>', ($tmpin = "a2pin.$$")) ||
open(TMPIN, '>', ($tmpin = "/tmp/a2pin.$$")) ||
die "can't find a tmp input file";

open(TMPOUT, '+>', ($tmpout = "a2pout.$$")) ||
open(TMPOUT, '+>', ($tmpout = "/tmp/a2pout.$$")) ||
die "can't find a tmp output file";
my ($tmpin_fh, $tmpin) = tempfile();
my ($tmpout_fh, $tmpout) = tempfile();

# And some people think getopts does everything. Sheesh.
while (@ARGV) {
Expand Down Expand Up @@ -86,7 +79,7 @@ while (@ARGV) {
next;
}
else {
print TMPIN "$_\n";
print {$tmpin_fh} "$_\n";
shift;
push @nargs, $tmpin;
last;
Expand All @@ -96,9 +89,9 @@ while (@ARGV) {

unshift @ARGV, @vargs; # put back var=val statements

close(TMPIN) || die "can't close $tmpin: $!";
close($tmpin_fh) or die "can't close $tmpin: $!";

open(STDOUT, '>&', TMPOUT) || die "can't dup to $tmpout: $!";
open(STDOUT, '>&', $tmpout_fh) or die "can't dup to $tmpout: $!";
$| = 1;

system 'a2p', @nargs;
Expand All @@ -113,13 +106,13 @@ the App::a2p module.
HERE
}

die "empty program" unless -s TMPOUT;
die "empty program" unless -s $tmpout_fh;
die "empty program" unless -s $tmpout;

seek(TMPOUT, 0, 0) || die "can't rewind $tmpout: $!";
$program = do { local $/; <TMPOUT> };
close(TMPOUT) || die "can't close $tmpout: $!";
open(STDOUT, '>&', SAVE_OUT) || die "can't restore stdout: $!";
seek($tmpout_fh, 0, 0) or die "can't rewind $tmpout: $!";
$program = do { local $/; <$tmpout_fh> };
close($tmpout_fh) or die "can't close $tmpout: $!";
open(STDOUT, '>&', SAVE_OUT) or die "can't restore stdout: $!";

eval qq{
no strict;
Expand All @@ -131,7 +124,6 @@ if ($@) {
die "Couldn't compile and execute awk-to-perl program: $@\n";
}

unlink $tmpin, $tmpout;
exit 0;

__END__
Expand Down

0 comments on commit 669a776

Please sign in to comment.