简体   繁体   English

Perl中没有提供文件名时如何使用__DATA__句柄

[英]How to use the __DATA__ handle when no filename supplied in perl

Looking for a way using the DATA handle if no filename provided to the perl script. 如果没有为perl脚本提供文件名,则寻找使用DATA句柄的方法。

I'm not very skilled in perl. 我不太擅长Perl。

Something like: 就像是:

use strict;
use warnings;
use autodie;
use diagnostics;

my $fd;
if( $ARGV[0] && -f $ARGV[0] ) {
    open $fd, "<", $ARGV[0];
} else {
    $fd = "DATA";   #what here?
}

process($fd);
close($fd); #closing the file - or the DATA handle too?

sub process {
    my $handle = shift;
    while(<$handle>) {
        chomp;
        print $_,"\n";
    }
}

__DATA__
default content

$fd=\\*DATA ; $fd=\\*DATA ; should do the trick 应该可以

You may prefer to default to the DATA handle if the file open fails instead of letting autodie stop your program. 如果文件打开失败,您可能更喜欢默认使用DATA句柄,而不是让autodie停止程序。 That is a better test anyway than -f . 无论如何,这是比-f更好的测试。 Something like this perhaps 像这样的东西

my $fd = \*DATA;
if (@ARGV) {
  if (open $_, '<', $ARGV[0]) {
    $fd = $_;
  }
  else {
    warn qq{Unable to open "$ARGV[0]" for reading: $!};
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM