2015-03-25 73 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。但是,在這種情況下,它可能會幫助您看到您的錯誤。