#!/usr/bin/perl

# writeToTempFile:
# This script writes the text supplied on the command-line or via STDIN
# to a temporary file and outputs the name of that file (to STDOUT)
# It is mostly intended as an illustration of how to write to temp files
# in a secure way, avoiding race conditions.
# In a more usual usage, you would use 'unlink' to remove the file afterwards.
#
# Cameron Hayne (macdev@hayne.net)  Oct 2006

use strict;
use warnings;

# writeStringToTempFile: saves the given string to a temp file
#                        and returns the name of that file
sub writeStringToTempFile($)
{
    my ($str) = @_;
    
    use File::Temp qw(tempfile);
    
    my ($fh, $filename) = tempfile();     
    print $fh $str;
    $fh->close();
    
    return $filename;
}

MAIN:
{
    my $text;
    if (@ARGV)
    {
        $text = join(" ", @ARGV);
    }
    else
    {
        $text = join("", <STDIN>);
    }

    my $tempFile = writeStringToTempFile($text);
    print "tempFile: $tempFile\n";
}
