在./script第17行没有这样的文件或目录

Aus*_*ore 3 perl file-io

确切的错误:

$ ./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:
Run Code Online (Sandbox Code Playgroud)

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

#!/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";
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果我更换ARGV[0]"file.txt"或类似的东西,打印到文件工作正常.如果我不提供文件名,脚本工作正常.我的预感是print语句干扰了iostream缓冲区,但我无法弄清楚如何修复它.

cho*_*oba 5

这就是魔术钻石操作员在Perl中的工作方式.如果使用参数启动脚本,它会尝试从文件中读取输入.如果您输入标准输入,则从那里读取.