How Do I Point a File Handle to STDOUT (or Another File Handle) In Perl?

前端 未结 5 1810
不知归路
不知归路 2021-01-31 18:19

I want to make a quick script that writes to a file if a file is given, or stdout if no file is given. It would be much easier for me to do this if I could start the script by p

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 18:52

    - is magic. Follow the convention or you violate the principle of least surprise.

    use autodie qw(:all);
    use Getopt::Long qw(GetOptions);
    GetOptions(\my %opt, 'out=s') or die 'usage';
    die 'usage' unless $opt{out};
    open my $handle, ">$opt{out}";
    

    perl foo -o blahblah        # opens file blahblah for writing
    perl foo -o -               # goes to STDOUT
    

    Related: Are there reasons to ever use the two-argument form of open(...) in Perl?

提交回复
热议问题