I am having a perl script which opens a file and write some data in it. Sometimes this file is having read only permissions on some machines. For such cases, at present the script dies as it was not able to open the file. My requirement is that in such cases, I want my script to continue and instead of writing the contents in file, puts it in STDOUT. I will use the warn instead of die, but I want to know can I alias my file handle FILE1 to STDOUT such that I need not have to modify the remaining code, reason being in my actual code print FILE1 <> is present at many places and is not possible for me to put if\else conditions everywhere. I want that I will alias FILE1 to STDOUT such that print statement will either output it in STDOUT or write in file depending upon the value set in FILE1 filehandle. Is it possible using perl?
$file = "testfile.txt";
open( FILE1, ">> $file" ) or die "Can not read file $file: $! \n";
print FILE1 "Line1 \n";
print FILE1 "Line2 \n";
print FILE1 "Line3 \n";
print FILE1 "Line4 \n";
close FILE1