develooper Front page | perl.perl5.porters | Postings from October 2016

Re: Temporary files with open my $fh, ">", undef;

Thread Previous | Thread Next
From:
Dan Book
Date:
October 26, 2016 16:09
Subject:
Re: Temporary files with open my $fh, ">", undef;
Message ID:
CABMkAVVu7KafFrFxW5_dpjLVo1nvktK_8BAUXmtn0Xa983d03A@mail.gmail.com
On Wed, Oct 26, 2016 at 10:26 AM, Andy Lester <andy@petdance.com> wrote:

> In this thread on /r/perl https://www.reddit.com/r/perl/comments/59hii9/
> how_to_empty_a_file_with_perl/, it’s noted that
>
>     Another trick which I recently discovered (after looking at a
> benchmark script written by MJGARDNER) is that you can use undef as the
> filename in the 3-argument open:
>
>      open my $fh, ">", undef;
>
>     this creates an anonymous temporary file. This alleviates the need to
> use File::Temp.
>
> Looking at perlfunc -o open, we find
>
>             As a special case the three-argument form with
> a read/write mode
>             and the third argument being "undef":
>
>                 open(my $tmp, "+>", undef) or die ...
>
>             opens a filehandle to an anonymous temporary file. Also using
> "+<"
>             works for symmetry, but you really should consider writing
>             something to the temporary file first. You will need to "seek"
> to
>             do the reading.
>
> I read this to mean the mode must be “+>” or “+<“ for the anonymous
> temporary file.  Should the docs also mention that “>” works as well?  Or
> should “>” not work, and the fact that it DOES work is a bug?
>
>
My assumption would be that they aren't mentioned because opening it for
only reading is useless because it doesn't exist, and for only writing is
useless because you don't know what its filename is; you might as well just
open the handle to /dev/null.

-Dan

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About