On Tue, Sep 24, 2002 at 12:15:08PM -0400, Erik Price wrote:
> 
> PS: I'm trying to think of an elegant and simple way to read <STDIN> if 
> there is any standard input and read <DATA> if not.  Yes, I could just 
> test for <STDIN> != "" or something and use "if" statements, but that 
> would basically mean repeating the same chunk of code with a different 
> file handle inside the <>.  Any good ideas that let me just use the 
> same block in either case?

You haven't said much about your problem, but you can use a simple
variable in <> such as:

$fh = is_there_any_standard_input() ? \*STDIN : \*DATA;
while (<$fh>) {
   ...
}

Or in one step (fails on old Perls):

while (readline(is_there_any_standard_input() ? \*STDIN : \*DATA)) {
   ...
}

You can't use angle brackets for expressions like this, because Perl
regards them as the glob() operator.  readline($fh) is the same as
<$fh>.

How you detect whether "there is any standard input" (or what you mean
by that) is another interesting question.  Here is one answer.

sub is_there_any_standard_input {
    return (-f(STDIN) || -p(STDIN)); # true if STDIN is a file or pipe
}

Hope this helps.

-- 
John Tobey <[EMAIL PROTECTED]>
\____^-^
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm

Reply via email to