Programmatically read from STDIN or input file in Perl

前端 未结 8 1096
南方客
南方客 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:01

    The "slickest" way in certain situations is to take advantage of the -n switch. It implicitly wraps your code with a while(<>) loop and handles the input flexibly.

    In slickestWay.pl:

    #!/usr/bin/perl -n
    
    BEGIN: {
      # do something once here
    }
    
    # implement logic for a single line of input
    print $result;
    

    At the command line:

    chmod +x slickestWay.pl
    

    Now, depending on your input do one of the following:

    1. Wait for user input

      ./slickestWay.pl
      
    2. Read from file(s) named in arguments (no redirection required)

      ./slickestWay.pl input.txt
      ./slickestWay.pl input.txt moreInput.txt
      
    3. Use a pipe

      someOtherScript | ./slickestWay.pl 
      

    The BEGIN block is necessary if you need to initialize some kind of object-oriented interface, such as Text::CSV or some such, which you can add to the shebang with -M.

    -l and -p are also your friends.

提交回复
热议问题