Programmatically read from STDIN or input file in Perl

前端 未结 8 1078
南方客
南方客 2020-12-12 19:45

What is the slickest way to programatically read from stdin or an input file (if provided) in Perl?

相关标签:
8条回答
  • 2020-12-12 20:07

    You need to use <> operator:

    while (<>) {
        print $_; # or simply "print;"
    }
    

    Which can be compacted to:

    print while (<>);
    

    Arbitrary file:

    open F, "<file.txt" or die $!;
    while (<F>) {
        print $_;
    }
    close F;
    
    0 讨论(0)
  • 2020-12-12 20:16

    Here is how I made a script that could take either command line inputs or have a text file redirected.

    if ($#ARGV < 1) {
        @ARGV = ();
        @ARGV = <>;
        chomp(@ARGV);
    }
    


    This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.

    WARNING

    If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.

    I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.

    0 讨论(0)
提交回复
热议问题