Run it without any flags and you get a "Can't unlink file" message because the END block doesn't have a file name to unlink. So the END block is being queued for execution at compile time like the documentation says.
Run it with the flag and the file name is known in the END block and the file gets unlinked. Obviously the END block was queued at run time, which is not what the documentation would lead me to believe should happen.
I'd even be okay with it if the END blocks were queued up both when compiling and when calling the function. If that were the case though, I should see the "Can't unlink" error even when passing the -r flag.
I can stop the error message by wrapping the code in the END block with an if ($name){} block, but does anybody understand what's really going on here? I suspect it's some DWIM magic, but it's causing me more confusion than I'd like.
Thanks,
--Larry
#!/usr/bin/perl die "Usage: $0 -r\n" unless ( grep /^-r$/, @ARGV); my $testingfile = new_tmpfile_name(); print "Pretending to do something with $testingfile...\n"; exit 0; #-------------------------------------------------------------------- # Make up a temporary file name that is not already in use # elsewhere and arrange for it to be deleted automatically when # the program exits. # # This will get you in trouble if you ever use it with mod_perl. # BTW: 90% of this is stolen from the Ram recipe number 7.5 #-------------------------------------------------------------------- sub new_tmpfile_name { use IO::File; use POSIX qw(tmpnam); my ($name, $fh); # try new temp filenames 'til we get one that doesn't exist do { $name = tmpnam() } until $fh = IO::File->new($name, O_RDWR|O_CREAT|O_EXCL); # install atexit-style handler so that when we exit or die # we automatically delete this temporary file END { unlink($name) or die "Couldn't unlink $name : $!" } return $name; }
In reply to END blocks created at run time? by lemmett
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |