Regex 提示用户输入文件并返回一系列信息时出现问题[Perl]
我正在尝试创建一个简单的程序来完成这五件事Regex 提示用户输入文件并返回一系列信息时出现问题[Perl],regex,perl,input,sum,output,Regex,Perl,Input,Sum,Output,我正在尝试创建一个简单的程序来完成这五件事 提示用户输入文件 如果用户指定未知文档,则提示用户文件不存在(情况1) 该文件不是常规文件(案例2) 打开用户提交的文件时出现问题(案例3) 指定的文件有(1)个数据不是有效数字,或(2)行上有多个数字。(案例4) 该文件已存在,并且可以无错误地打开。文件必须包含一个数字(任何十进制或负/正整数),并计算总和、文件中的数字数以及平均值/平均值(情况5) 我已经在我提供的代码上标记了这些案例。每次运行这个程序时,我都不会得到错误,但会得到相同的响应。我试
#!/usr/bin/perl
use strict;
use warnings;
print ("Enter a file name: ");
my $infile = <STDIN>; #Prompts the user for input
chomp ($infile); #Chomps the $infile Variable.
#****CASE ONE****
if (-e $infile) {
print ("File '$infile' does not exist.\n");
exit;
}
#****CASE TWO****
elsif (-f $infile) {
print ("Not a regular file or directory.\n");
exit;
}
#****CASE THREE****
open ( my $input, '<', $infile ) or die $!;
print ("Can not open input file '$infile': Permission denied. ");
#****CASE FOUR****
#for (my $inf = 1; ; ++$_)
my $inf = 9**9**9;
if (-e $infile =~ /^[a-zA-Z]+$/) {
} else {
print ("File '$infile' containts invalid data.\n");
exit;
}
#****Case Five****
my $Int_Pos = 0;
my $Int_Neg = 0;
my $Int_Dec = 0;
open(FHIN, '<', $infile); #Opens the file prompted by user.
my @lines = <FHIN>; #Variable storing the number of lines in the file.
chomp( @lines );
close(FHIN); #File handle is closed.
while (my $line = <$input> ) { #iterates the file line by line, making $_ as teh defaule variable.
$Int_Pos++ if $line >= 0;
$Int_Neg++ if $line >= 0;
$Int_Dec++ if $line >= 0;
my $sum = $Int_Pos + $Int_Neg + $Int_Dec;
my $Observations = @lines;
my $Mean = $sum/3;
print ("Sum: '$sum'\n");
print ("Observations: '$Observations'\n");
print ("Mean: '$Mean'\n");
}
#/usr/bin/perl
严格使用;
使用警告;
打印(“输入文件名:”);
我的$infle=#提示用户输入
chomp($infle)#Chomps$infle变量。
#****案例一****
如果(-e$infle){
打印(“文件“$infle”不存在。\n”);
出口
}
#****案例二****
elsif(-f$infle){
打印(“不是常规文件或目录。\n”);
出口
}
#****案例三****
打开(my$input),您正在使用$infle作为输入
#****CASE THREE****
open ( my $input, '<', $infile ) or die $!;
案例三****
打开(我的$input,“好的,所以有多处错误:
如果(-e$infle)
应该
`if (not -e $infile) `
elsif(-f$infle)
的测试问题与您想要的相反elsif(而不是-f$infle)
此外,此打印将在文件打开时进行:`
open ( my $input, '<', $infile ) or die $!;
print ("Can not open input file '$infile': Permission denied. ");`
open(我的$input),“每次运行这个时,我都不会得到错误,但会得到相同的响应。”那是哪个响应?对于确实存在的文件和“没有这样的文件或目录”的文件,可能是“文件不存在”对于不存在的文件。您的逻辑是不可靠的:-e
和-f
表示文件确实存在,您在成功打开文件后打印“权限被拒绝”,等等。是的;我的返回值是“file doe not exist”。我将如何使用-e和-f运算符(如果该文件实际上不存在,则返回正确的消息)?“该文件必须包含单个数字…并计算总和、文件中的数字以及平均数/平均数”你想计算一个数字的总和和平均数吗?这是家庭作业吗?所有这些标准的最佳测试就是打开文件并报告任何错误。你的代码和你的单词之间存在认知上的不一致。也就是说,你说的东西与你的代码试图做的不匹配。处理每个错误,我刚才给你的家庭作业的起点OP的部分代码实际上很好。他们希望打开用户指定的文件,而不是硬编码的文件名。
open ( my $input, '<', $infile ) or die $!;
print ("Can not open input file '$infile': Permission denied. ");`
`open ( my $input, '<', $infile ) or die("Can not open input file '$infile': $!");`