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

Hi all, I am trying to use a file if a file is given by the user, otherwise use STDIN. It is not working, and I am not sure of the best way to do this. I could use some advice. I suspect I need some honing of my understanding of using variables with filehandles.

if ($FILE) { open(FILE,"<",$FILE) || fatal_error("Unable to open file $FILE"); $HANDLE='FILE' } else { $HANDLE='STDIN'; } ###################################################################### +########## #MAIN ###################################################################### +########## while (defined(my $line = <$HANDLE>)) { print "$line"; }

Replies are listed 'Best First'.
Re: How to select a file handle depending on user options
by choroba (Cardinal) on Jun 18, 2012 at 21:53 UTC
    You assign strings 'FILE' and 'STDIN' instead of handles. Use
    $HANDLE = *FILE; ... $HANDLE = *STDIN;
    Update: or use \*FILE for a reference.

    See Typeglobs and Filehandles.

Re: How to select a file handle depending on user options
by morgon (Priest) on Jun 18, 2012 at 23:14 UTC
    You handle STDIN wrong (you need a filehandle or a typeglob - not a string) and it is usually better to use lexical variables for filehandles.

    One way of doing it would be:

    use IO::File; my $handle = $FILE ? do { IO::File->new($FILE) or fatal_error(".."); } : *STDIN; # later you can use <$handle>
      so IO::File->new returns the file handle? I have never seen do used in a ternary like that. Interesting. Thank you.
Re: How to select a file handle depending on user options
by linuxkid (Sexton) on Jun 19, 2012 at 20:29 UTC

    use the <> operator in while, and it will set $_

    --linuxkid


    imrunningoutofideas.co.cc