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

Hi guys !

I need to manipulate a specific file I have. For that I have a temporary file that I print the new information I created from the original, at the end I'd like to print this file (and I don't need it any more - the tmp one). Is there a way I can do that without using a tmp file (maybe with pipes or something else). The new info isn't created by a system command.

BTW, I'd like to print the new info in one piece, and not while creating the new info (in a loop).

Thanks.

Hotshot

Replies are listed 'Best First'.
Re: temporary file
by rob_au (Abbot) on May 19, 2002 at 12:56 UTC
    See Using Temporary Files in Perl for a discussion on secure and robust methods for creating and manipulating temporary files.

    Based upon your described requirements, the following code using the new_tmpfile method of IO::File may suffice:

    use IO::File; my $fh = IO::File->new_tmpfile; . . . $fh->seek(0, 0); print STDOUT $_ foreach <$fh>; $fh->close;

    This code creates a temporary file using the new_tmpfile method of IO::File - This method creates a temporary file, based on the POSIX tmpfile() function or tmpfile() from glibc if using Perl I/O abstraction, and then, where possible, unlinks the file while still holding it open. The result is an anonymous file handle suitable for the temporary storage of data - The data is stored in a stdio stream. The only disadvantage with this method of file name generation is that the temporary file cannot be referenced other than through the returned file handle.

    The perlfunc:seek function is then used to move the current read/write pointer within the file back to the start of the file, allowing the process output to be re-read in full for reporting to STDOUT.

     

Re: temporary file
by dree (Monsignor) on May 19, 2002 at 13:00 UTC
    Hello! :)

    You can use pipes | to send a program output to (another) program input.
    For example to send an attach with sendmail via CGI, without using a temporary file to mimencode the attach, you can pipe the output from cat to the input of mimencode:
    #code from a sub unless (open(MAIL, "| $sendmail ")) { return 0 }; my $attach=$q->param('upfile'); my $path = $q->tmpFileName($attach); open (ATTACH,"cat $path | mimencode |") or return 0; [cut] close ATTACH; close MAIL;
Re: temporary file
by particle (Vicar) on May 19, 2002 at 12:59 UTC
    you might also want to look at perlrun for the -i -- inplace edit option. if that doesn't suit your needs, rob_au provided some good working code.

    ~Particle *accelerates*

Re: temporary file
by vek (Prior) on May 19, 2002 at 12:50 UTC
    Depending on the size of your data you could always keep the new data in an array and then just print that. Obviously if you're talking about huge amounts of data an array would not be a good idea.

    -- vek --