http://www.perlmonks.org?node_id=808423

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

Hi Monks,

I learned about three-way open and wanted to use it. Everything seemed OK. Then I encountered problems with one particular script. It opens a file and writes to it. Normally no problem. The usage, however, caused some problems.

The script is used in the following two ways:
C:\>perl script.pl outfile C:\>perl script.pl ">outfile"
The second is used to append the data produced by the script to the already existing data.

Hmm... Three-way open brought me from open $filehandle ">$outfile" to open $filehandle ">", $outfile" which causes the trick not to work anymore.


First take on it:
my $openmode = '>'; if($outfile =~ m/\A>/xms) { $openmode = '>>'; $outfile =~ s/\A>//xms; } open($filehandle, $openmode, $outfile);
Any suggestions how to do this more elegant?

UPDATE: as per comment of bellaire (>outfile changed to ">outfile").