无法提示用户输入文件,并返回一系列信息[Perl]

时间:2017-02-14 18:54:59

标签: regex perl input sum output

我正在尝试创建一个执行这五件事的简单程序

  1. 提示用户输入文件。
  2. 如果用户指定了未知文档(案例1)
  3. ,则提示用户文件不存在
  4. 该文件不是常规文件(案例2)
  5. 打开用户提交的文件时遇到问题(案例3)
  6. 指定的文件包含(1)非有效数字的数据,或(2)行上的多个数字。 (案例4)
  7. 该文件存在且可以打开而没有错误。该文件必须包含单个数字(任何小数或负/ pos整数),并计算文件中的总和,数字和平均值/平均值(案例5)。
  8. 我已经在我提供的代码上标注了案例。每次我运行这个,我都不会得到错误,但回复的反应相同。我正在尝试这样来提高我的文件扫描技能。如果有人对这个话题有任何了解,我将不胜感激。提前致谢。

    #!/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");  
    }
    

2 个答案:

答案 0 :(得分:0)

好的,所以有很多错误:

if (-e $infile)应该是

`if (not -e $infile)  `

elsif (-f $infile)与测试您想要的elsif (not -f $infile)

相反的问题相同

此外,当文件打开时会发生此打印:`

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': $!");`

这一行是荒谬的if (-e $infile =~ /^[a-zA-Z]+$/)     我在第4种情况下猜测你会想要一些东西      foreach $line (<$infile >){ $matches = () = $line =~ /^(\d+)$/; if($matches != 1){ die "line does not contain a single number"; } $sum += $1; }

这是一个仓促,近似的代码,不使用严格(你应该使用严格!),这应该可以帮助你找出其余的

答案 1 :(得分:-1)

您使用$ infile作为输入

#****CASE THREE****
open ( my $input, '<', $infile ) or die $!;

我会做这样的事......

open ( my $input, '<', "somefile.txt" ) or die $!;