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

# I am trying to duplicate the STDIN as follows: # Why is it that the filehandle FH is empty? # How do I solve this? # The script is invoked as follows: # script_name.pl <input_file # I can't see anymore...I've got blisters on my fingers. open(FH,"<&STDIN") || die "Error with copying STDIN to FH : $!\n"; while ($inbuf=<STDIN>) { print $inbuf; } while (<FH>) { print $_; } close(FH) || die "Error closing FH: $!\n"; exit;

Replies are listed 'Best First'.
Re: Duplicating STDIN
by RMGir (Prior) on Aug 23, 2002 at 23:40 UTC
    You're going to kick yourself, I think...

    By the time you use FH, STDIN consumed all the data in the file. I would have thought they'd have separate locations in the file, but I guess that doesn't make sense, since output dupes don't.

    It works fine if you seek FH back to the start of the file, but then, you could just seek STDIN the same way:

    open(FH,"<&STDIN") || die "Error with copying STDIN to FH : $!\n"; while ($inbuf=<STDIN>) { print $inbuf; } seek FH,0,0; while (<FH>) { print $_; } close(FH) || die "Error closing FH: $!\n"; exit;
    Here it is with STDIN twice:
    while ($inbuf=<STDIN>) { print $inbuf; } seek STDIN,0,0; while (<STDIN>) { print $_; } exit;
    Both work fine.
    --
    Mike
Re: Duplicating STDIN
by Mr. Muskrat (Canon) on Aug 23, 2002 at 23:45 UTC
    If all you want to do is print from standard input then try this:
    #!/usr/bin/perl -w use strict; while (<>) { print $_; }
    It boils to Perl reading from the files listed on the command line or from the keyboard (don't forget Ctrl-Z to end in that case).

    <Update>I forgot to mention that it can be called like this: script_name.pl input_file