【发布时间】:2015-09-21 14:22:12
【问题描述】:
我正在为学校做一个项目,这门课非常不具描述性。我不明白发生了什么以及为什么我无法显示文件。
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
print "\n+--------------------------+";
print "\n| The File Search & |";
print "\n| Display Tool |";
print "\n+--------------------------+";
print "\nPlease enter the file you would like to read (with full path): \n";
my $FILE = <STDIN>;
chomp $FILE;
sleep 1;
open (FILE, "$FILE");
print " Here is the secret information you seek supreme leader: \n";
print "==============================================================";
while ($FILE) {
chomp $FILE;
open $FILE;
}
我不完全确定我做错了什么。我尝试了各种不同的组合,但它只会导致错误。
更新
所以我根据大家的建议对代码进行了一些修改(见下文)。运行脚本后返回以下错误
readline() on unopened filehandle at test.pl line 30.
在下面的代码中,我想我打开了文件句柄,但这个错误让我觉得我在打开命令附近的某个地方搞砸了。
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
print "\n+--------------------------+";
print "\n| The File Search & |"; #Not so fancy banner!
print "\n| Display Tool |";
print "\n+--------------------------+";
print "\n Welcome to the Tool. It is still being tested!!\n";
print "\n Please enter the file you would like to read: ";
my $filename = <STDIN>; #define the variable for the filename
if ( not -f $filename ) #This checks the validity of the file
{
print "Filename does not exist\n";
exit;
}
sleep 1;
print " Here is the secret information you seek supreme leader: \n";
print "==============================================================\n";
open my $filehandle, "<", $filename; #or die $!
while ( <$filename> ) { #While loop to read each line of the file
chomp;
print "$_\n";
}
我注释掉了打开字符串的 or die 部分,因为它只是杀死了脚本,我想看看有什么问题。我对 open 语句中的“
【问题讨论】:
-
我只能说 - 通常家庭作业问题意味着不好的问题。这实际上是一个很好的问题,而且很明确且可以回答。
-
@Borodin 对这个错误有什么建议吗?
-
您应该真正打开一个新问题,而不是更新现有问题——Stack Overflow 与论坛非常不同。这里有两个问题。如果
or die正在杀死脚本,那么这意味着打开由于某种原因而失败,并且尝试从句柄中读取是没有意义的。其次,您有<$filename>,这是对原始代码的回归:您无法从文件名中读取!我还建议使用$fh而不是$filehandle,因为后者在视觉上与$filename没有太大区别 -
可能不清楚的地方 --
<$fh>是文件句柄上的readline$fh -
open调用有一个、两个和三个参数形式。第一个非常古老,最好被遗忘。第二个大概是你熟悉的,打开模式与文件名混在一起,你写open my $fh, '<myfile.txt',你可以省略<作为读取模式。这仍然是一个小技巧,最后一种形式现在被认为是最佳实践,其中每条输入都是分开的。这意味着您可以打开名称为<的文件,这些文件在 Linux 平台上有效,但无法以任何其他方式打开
标签: perl