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

Hello Monks,

I wrote a program that reads from an input file and that write hte output to another file.To give it more versatility, I want to see if there is an argument specifying the pathes and names of the files otherwise to read from STDIN and STDOUT. I sort of successed in doing that even though I don't know if is the most beautiful code. I just have a warning I can't get rid of.

Example of code and error message provided

Here is an example I wrote just to show you, so it doesn't actually do anything. However it outputs the warning produces by the pragma diagnostics (so I know that if I would get rid of the pragma, I would get rid of the message, but is that moral :-) )

Here is the code

#!/usr/bin/perl -w use strict; use warnings; use diagnostics; use Benchmark; use Getopt::Long qw(:config no_ignore_case bundling); #defines variables my $man = 0; my $help = 0; my $input; my $output; my @blubb; my %options = ( 'help|h' => \$help, 'man' => \$man, 'input|i=s' => \$input, 'output|o=s' => \$output, ); GetOptions(%options); open STDIN, "<$input" or die "Can't open $input: $!" if $input; while(<STDIN>) { chomp; push @blubb, $_; } close STDIN if $input; open STDOUT, ">$output" or die "Can't open $output: $!" if $output; print join "\n", @blubb; print "\n"; close STDOUT if $output; exit 0;

And here is the error message

Filehandle STDIN reopened as STDOUT only for output at ex.pl line 36 ( +#1) (W io) You opened for writing a filehandle that got the same filehandl +e id as STDIN. This occured because you closed STDIN previously.

I don't understand this error message as I don't touch STDIN at line 36.
Anyone has a clue about the reason?

Thanks in advance

--
jey

Replies are listed 'Best First'.
Re: problem of filehandling
by Abigail-II (Bishop) on Jan 27, 2004 at 13:33 UTC
    What part of This occured because you closed STDIN previously. don't you understand? You do close STDIN two lines above it.

    As for opening STDIN yourself, you could make use of the magic of the open command. If you open a file called "-", Perl will read from standard input. For instance:

    Getoptions (...); $input = "-" unless defined $input; open my $fh => $input or die $!; while (<$fh>) { ... }

    Abigail