Getting argument as filename or STDIN

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lilly07
    New Member
    • Jul 2008
    • 89

    Getting argument as filename or STDIN

    I am trying to read a file. The file contents can be either STDIN or a file name.

    When it is from a file, I open as follows.
    Code:
    Open filename ($filename)
    While(<$filename>){
    #process each line
    }
    Otherwise if it is from STDIN, I always use
    Code:
    while(<>){
    #process each line
    }
    Now my constraint is the user can either specify the file name or pipe as STDIN from another program. How to handle that situation in the same script?


    My perl program has the usage as below.

    Perl converter.pl --in file <filename or STDIN> --out file <out filename>

    Please let me knowhow to handle this. Thanks.
    Last edited by numberwhun; Nov 27 '10, 09:30 PM. Reason: Please always use code tags.
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    First, when someone pipes output to your perl script, it will probably be similar to this:

    Code:
    cat file.txt | script.pl
    In this case, the input to the perl script can actually be caught using the STDIN filehandle. In other words, if the user cats the file they wish to process with your script and pipes it to your file, you could simply:

    Code:
    while(<STDIN>){
        some code;
    }
    To handle both I would test to see if the command line options are set and if not, then reference STDIN instead.

    Regards,

    Jeff

    Comment

    • lilly07
      New Member
      • Jul 2008
      • 89

      #3
      Thanks forr your help Jeff.

      Comment

      • rovf
        New Member
        • May 2010
        • 41

        #4
        Well, your "open" statement isn't even valid Perl, but anyway:

        You could set up a file handle like this (warning, code not tested):

        Code:
        my $input = *STDIN;
        if($read_from_file) {
          open(FH,...);
          $input = *FH;
        }
        and read from <$input>.

        Comment

        Working...