tags:

views:

101

answers:

2

I am trying to create a temp file using the following code:

 use File::Temp  ;
 $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX',
                        DIR => 'mydir',
                        SUFFIX => '.dat');

This is create the temp file. Because of my permission issue, the other program is not able to write into file.

So I just want to generate the file name without creating the file. Is there any where to do that?

+5  A: 

If you don't create the file at the same time you create the name then it is possible for the a file with the same name to be created before you create the file manually. If you need to have a different process open the file, simply close it first:

#!/usr/bin/perl

use strict;
use warnings;

use File::Temp;

sub get_temp_filename {
    my $fh = File::Temp->new(
        TEMPLATE => 'tempXXXXX',
        DIR      => 'mydir',
        SUFFIX   => '.dat',
    );

    return $fh->filename;
}

my $filename = get_temp_filename();

open my $fh, ">", $filename
    or die "could not open $filename: $!";

The best way to handle the permissions problem is to make sure the users that run the two programs are both in the same group. You can then use chmod to change the permissions inside the first program to allow the second program (or any user in that group) to modify the file:

my $filename = get_temp_filename();

chmod 0660, $filename;
Chas. Owens
+4  A: 

Just to obtain the name of the tempfile you can do:

#!/usr/bin/perl
use strict;
use warnings;
use 5.10.1;

use File::Temp qw/tempfile/;

my $file;

(undef, $file) = tempfile('tmpXXXXXX', OPEN=>0);

say $file;

But as Chas. Owens said, be careful the same name could be created before you use it.

M42