2015-03-25 42 views
-3

我得到以下错误的使用方法:

Use of uninitialized value $_ in concatenation (.) or string at checkfornewfiles.pl line 34. 

试图运行下面的代码时:

#!/usr/bin/perl -w 
#Author: mimo 
#Date 3/2015 
#Purpose: monitor directory for new files... 

AscertainStatus(); 
     ######### start of subroutine ######## 
sub AscertainStatus { 
    my $DIR= "test2"; 

    ####### open handler ############# 
    opendir (HAN1, "$DIR") || die "Problem: $!"; 

    ########## assign theoutput of HAN1 to array1 ########## 
    my @array1= readdir(HAN1); 

    ######## adding some logiC######### 

    if ("$#array1" > 1) { #### if files exists (more than 1) in the directory ####### 
      for (my $i=0; $i<2; $i++) {shift @array1;}  ####### for i in position 0 (which is the . position) loop twice and add one (the position ..) get rid of them ####### 
      MailNewFiles(@array1); 
    }  else { print "No New Files\n";} 

} 

sub MailNewFiles { 
    $mail= "sendmail"; 

    open ($mail, "| /usr/lib/sendmail -oi -t") ||die "errors with sendmail $!"; # open handler and pipe it to sendmail 
    print $mail <<"EOF"; #print till the end of fiEOF 
    From: "user"; 
    To: "root"; 
    Subject: "New Files Found"; 

    foreach (@_) {print $mail "new file found:\n $_\n";} 
EOF 
    close($mail); 
} 

#End 

我是新perl,我不知道发生了什么问题。谁能帮我 ?

回答

0

您有EOF后跟foreach。它包含$_这是插入在这里,但$_尚未初始化,因为它不在foreach循环。这不是代码而是文本。在foreach之前移动EOF。

,不过也许你想

sub MailNewFiles { 
    $mail= "sendmail"; 

    open ($mail, "| /usr/lib/sendmail -oi -t") ||die "errors with sendmail $!"; # open handler and pipe it to sendmail 
    local $"="\n"; # " make syntax highlight happy 
    print $mail <<"EOF"; #print till the end of fiEOF 
From: "user"; 
To: "root"; 
Subject: "New Files Found"; 

New files found: 
@_ 
EOF 
    close($mail); 
} 

更多信息,请参见perlvar$"

0

消息

Use of uninitialized value $xxx in ... 

是非常简单的。当你遇到它时,这意味着你正在以任何方式使用一个变量($ xxx),但这个变量还没有被初始化。

有时候,在你的代码开始添加一个初始化命令就足够了:

my $str = ''; 
my $num = 0; 

有时候,你的算法是错误的,或者你只是输错你的变量,像:

my $foo = 'foo'; 
my $bar = $ffo . 'bar'; # << There is a warning on this line 
         # << because you made a mistake on $foo ($ffo) 
4

一些建议:

  • Perl不是C.你的主程序循环不应该是一个声明的子程序,然后你 执行。消除AscertainStatus子例程。
  • 总是,总是use strict;use warnings;
  • 正确缩进。它让人们更容易阅读你的代码并帮助分析你做错了什么。
  • 使用更现代的Perl编码风格。 Perl是一种古老的语言,多年来,开发新的编码风格和技术可以帮助您消除基本错误并帮助其他人阅读代码。
  • 当有Perl模块可以以更标准的方式为你做这件事时,不要使用系统命令,并且可能做更好的错误检查。 Perl自带的Net::SMTP为您处理邮件通信。使用它。

错误Use of uninitialized value $_ in concatenation (.) or string正是它所说的。您正试图使用​​尚未设置的变量的值。在这种情况下,变量是foreach声明中的@_变量。您foreach是不是真正的foreach,但经过您for声明,因为你EOFprint语句的一部分是。这看起来像一个错误。

另外,@_的值是多少?该变量包含已传递给子例程的值列表。如果没有通过,它将是未定义的。即使@_未定义,foreach (undef)也会简单地跳过循环。但是,由于foreach (@_) {是要打印的字符串,因此您的Perl程序将会崩溃,而不会定义@_

如果从#!/usr/bin/perl删除-w,你的程序实际上将“工作”(注意引号),你会看到你的foreach将字面上打印。

我不建议您不要使用-w所做的警告。事实上,我建议你use warnings;而不是-w。但是,在这种情况下,它可能会帮助您看到您的错误。

相关问题