Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias file handle to STDOUT in perl

Tags:

perl

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
like image 994
sarbjit Avatar asked Apr 17 '13 13:04

sarbjit


1 Answers

You can do so with *FILE1 = STDOUT;.

Variables with a * in front are called typeglobs. Read about them here.

You may also want to start using lexical file handles

This is how i would solve your problem:

use strict;
use warnings;

my $file = "testfile.txt";
my $succ = open( my $fh , '>>', $file );

$fh = *STDOUT unless $succ;

print $fh "Line1 \n";
print $fh "Line2 \n";
print $fh "Line3 \n";
print $fh "Line4 \n";

close $fh if $succ; # don't close STDOUT
like image 114
tauli Avatar answered Sep 27 '22 20:09

tauli