3

确切的错误:

$ ./script.pl file.txt  
Can't open file.txt: No such file or directory at ./script.pl line 17. 
Use of uninitialized value in chomp at ./script.pl line 17. 
Username: Password:

我正在编写一个脚本,该脚本从命令行获取文件名,然后将其输出写入其中:

#!/usr/bin/perl
use warnings;
use strict;
use Term::ReadKey;

my @array;
my $user;
my $pass;

# get login info
print "Username: ";
chomp($user = <>); # line 17
print "Password: ";
ReadMode 2;
chomp($pass = <>);
ReadMode 0;
print " \n";

# ...
# connect to database, and save the info in "@array" 
# ...

# save the array to a file
if (defined($ARGV[0])) {
    open (MYFILE, ">".$ARGV[0]) or die "Can't open ".$ARGV[0].": $!\n";
    foreach (@array) {
        print MYFILE $_."\n";
    }
    close (MYFILE);
# otherwise, print the names to the screen
} else {
    foreach (@array) {
        print $_."\n";
    }
}

但是,如果我替换ARGV[0]"file.txt"或类似的东西,打印到文件就可以了。如果我不提供文件名,则脚本可以正常工作。我的预感是打印语句干扰了 iostream 缓冲区,但我不知道如何修复它。

4

2 回答 2

5

这就是 Perl 中魔法钻石运算符的工作原理。如果您使用参数启动脚本,它会尝试从文件中读取输入。如果你给它一个标准输入,它就会从那里读取。

于 2012-06-13T14:03:06.830 回答
3

如果您打算使用<STDIN>,请使用而不是从标准输入中读取。<>@ARGV

Or, even better, read directly from terminal (if STDIN is a terminal). A quick search brought up Term::ReadKey, but I haven't tried it myself.

于 2012-06-13T14:19:29.650 回答