Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

HI all, I feel this should be simple, But i can't seem to get any easy and straight forward solution to it!

I have got two strings(at times even three, actually depends on how the cgi form is filled) which I want to write to a temp file created as $fh = File::Temp->new(); even I tried without the File::Temp to hardcode the file path.

And I have to pass the file (with the two strings) to other subroutines.

But when I try to do that now, I get the file path passed to the subroutine instead of the file itself. Any suggestions and ideas would be greatly appreciated

Thanks for your time and suggestions

Replies are listed 'Best First'.
Re: to write string to a temp file
by keszler (Priest) on Feb 24, 2010 at 11:57 UTC
    From the documentation:
    filename

    Return the name of the temporary file associated with this object (if the object was created using the "new" constructor).

    $filename = $tmp->filename;
    This method is called automatically when the object is used as a string.
    When you use $fh in a string context, you get the filename instead. This was probably intended as a convenience...

    You could try passing the filehandle as a reference, or putting it into a hash or array for which a reference is passed.

Re: to write string to a temp file
by jethro (Monsignor) on Feb 24, 2010 at 12:06 UTC

    I guess with "pass the file" you mean "pass the filehandle"? That should not be a problem. The following

    perl -e 'use File::Temp; $fh = File::Temp->new(); $fh->unlink_on_destr +oy(0); bo($fh); sub bo { my $f= shift; print $f "test"; }'

    creates a file in /tmp with the string test in it.

    You might show us your code, generally it works

Re: to write string to a temp file
by cdarke (Prior) on Feb 24, 2010 at 12:17 UTC
    I have to pass the file (with the two strings) to other subroutines

    Do you mean the file handle? For example:
    use warnings; use strict; use File::Temp; sub mysub { my ($fh, $str1, $str2) = @_; $fh->seek( 0, 0 ); print <$fh>; } my $fh = File::Temp->new(); my $s1 = 'This is string one'; print $fh "$s1\n"; my $s2 = 'This is string two'; print $fh "$s2\n"; mysub ($fh, $s1, $s2);
    Gives:
    This is string one This is string two