Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Having an option to write to a file or STDOUT 1

Status
Not open for further replies.

wardy66

Programmer
Jun 18, 2002
102
AU
Hi all

I'm trying to think of the best way to write a script that can either output to a file or to STDOUT if no file name is supplied.

For example,
Code:
script.pl -o file.txt
would send the output to a file but
Code:
script.pl
would just print to the screen.

Inside script.pl I was thinking of something along the lines of
Code:
if ( $OUTFILE ) {
  open OUT, $OUTFILE
}
else {
  OUT = *STDOUT
}

# Print to file or screen, depending on whether $OUTFILE is set
print OUT "Hello world\n";
but is this the right idea? What if I close OUT - is this "impolite" since it might be going to STDOUT

Any comments or improvements on my idea are very welcome :)

Thanks
~ Michael
 
You can use the `select' function to change the default filehandle. Normally, when you call `print' without specifying a filehandle, it prints to STDOUT by default. `select' changes that. So:

Code:
open OUT, $OUTFILE;
select OUT;

print 'blah'; # this is printed to $OUTFILE

select STDOUT;
close OUT;

print 'blah'; # printed to STDOUT again
 
check the @ARGV array, if there is one then print to file, if not print to STDOUT.
 
Thanks Kevin but I use Getopt::Std to process all sorts of command line options. In the real script there are 2 output files, one of which can optionally be STDOUT.

So I need to look at what's passed as the value of -p and then decide whether to print or not.

As I put in my example above, I can get it to work by doing something like OUT = *STDOUT but it seemed a touch evil.

I was wondering about select() and also if the "&" forms of open() might be wise too.

Thanks
 
Why not something like the following?
Code:
if ($options{p} =~ /stdout/ || ! $options{p}) {
    select STDOUT;
} else {
    open FH, "< $options{p}" or die "Could not open file.\n$!\n";
    select FH;
}
This is untested; you might need to change the '|| !' bit to get the precedence right.
 
Thanks rharsh :)

I like that one. Might start using it from now on

Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top