在连接(。)或字符串at或字符串at处使用未初始化的值

时间:2014-08-21 08:44:13

标签: sql perl

我有这个错误:

Use of uninitialized value $index in concatenation (.) or string at getdesc.pl line 43, <OctetsIn> line 2.

我的代码的一部分如下:

my $select_sth = $dbh->prepare("SELECT Hid,Hostname,IP FROM Devices")
    or die "$dbh->errstr";
$select_sth->execute() or die "$dbh->errstr";
while ( my $row_ref = $select_sth->fetchrow_hashref ) {
    my $hostname = $row_ref->{'Hostname'};
    if ( $hostname ne 'null' ) {
        my $hid   = $row_ref->{'Hid'};
        my $ip    = $row_ref->{'IP'};
        my $desc  = "null";
        my $index = 0;
        open( OctetsIn, "snmpwalk -v2c -c public $ip 1.3.6.1.2.1.18 |" )
            or die "can't exec: $!";
        while (<OctetsIn>) {
            chomp;
            print <OctetsIn> . "\n";
            /IF-MIB::ifAlias.(\S+) = STRING: (\S+)/;
            $index = $1;
            $desc  = $2;
            $dbh->do(
                "INSERT INTO Description (Hid,index,desc) Values ($hid,$index,'$desc')"
            ) or die "$dbh->errstr";
        }
    }
}

close(OctetsIn);

我的代码中有什么错误?谁知道如何修复错误?

错误在线:

$dbh->do("INSERT INTO Description (Hid,index,desc) Values ($hid,$index,'$desc')") or die "$dbh->errstr";

3 个答案:

答案 0 :(得分:1)

在将$1分配给$index之前,您应该测试正则表达式是否成功,即

 # skip to next line if current did not match, as $1 and $2 are undefined
 /IF-MIB::ifAlias.(\S+) = STRING: (\S+)/ or next;

答案 1 :(得分:0)

$index = $1;

你的正则表达式不匹配,所以$ 1是undef

答案 2 :(得分:0)

最内层的while循环有三个问题:

  1. 在尝试打印当前行时,您从文件句柄中读取了两次:

    while (<OctetsIn>) {
        chomp;
        print <OctetsIn> . "\n";    # Should be: print "$_\n";
    
  2. 在使用捕获变量之前,请始终验证您的正则表达式是否匹配。

    /IF-MIB::ifAlias.(\S+) = STRING: (\S+)/;
    $index = $1;               # Will be undefined if regex doesn't match
    $desc  = $2;
    
  3. 使用placeholders and bind values而不是在SQL语句中手动包含值:

    应该永远不要将值直接插入到SQL语句中,如下所示:

    "INSERT INTO Description (Hid,index,desc) Values ($hid,$index,'$desc')"
    
  4. 为了清理这三个问题,我将内部while循环转换为如下所示。

    while (<OctetsIn>) {
        chomp;
        print "$_\n";
        if (my ($index, $desc) = /IF-MIB::ifAlias.(\S+) = STRING: (\S+)/) {
            $dbh->do(
                "INSERT INTO Description (Hid,index,desc) Values (?,?,?)",
                undef, $hid, $index, $desc
            ) or die $dbh->errstr;
        }
    }