2013-04-15 64 views
0

SO。Perl DBI - 使用未初始化的值

我使用Perl的DBI從Perl腳本查詢Oracle數據庫。我使用fetchrow_hashref獲取返回的行(因爲我稍後需要列名)。我把每個返回的行放入一個數組中,然後返回對該數組的引用。所以基本上我返回一個對散列引用數組的引用。事情是這樣的:

my $sth = $dbh->prepare($query); 
$sth->execute(); 

# Fetch all rows returned as hash references and put each of those 
# references into the array @rows 
@returned_rows =(); 
while ($row = $sth->fetchrow_hashref()) { 
    push(@returned_rows, $row); 
} 

# Return a reference to the array @rows 
# Return a reference to an array of hash references 
return \@returned_rows; 

如果領域之一當屬無效,我得到:

Use of uninitialized value in concatenation (.) or string at sqlesl.pl line 49. 

這是可以的,因爲我是從數據庫中預期空值,但即使我測試UNDEF ,我得到了同樣的錯誤,這讓我覺得事情並不像DBI文檔所說的那樣:

fetchrow_arrayref的替代方案。獲取下一行數據,並將其返回爲包含字段名稱和字段 值對的散列的引用。空字段在散列中作爲undef值返回。

這是我用來測試上面代碼片段的一段代碼。假設* $ rows_ref *是上面的代碼片段返回的內容。

@rows = @$rows_ref; 
$hash_ref = $rows[0]; 
%hash = %$hash_ref; 
@keys = keys %hash; 

foreach $key (@keys) { 
    next if (undef($hash{$key})); 
    print "$key: $hash{$key}\n"; 
} 

有人有一些光在這一個?

在此先感謝。

+1

請注意,您可以調用'$ sth-> fetchall_arrayref({})'得到hashref行的數組引用,這樣你就不會需要填充'@returned_rows '你自己 – stevenl

回答

2

undef是取消其參數的函數。在情況下,你應該使用defined代替:

next unless defined $hash{$key}; 
+1

@horhay可能也會考慮'存在$ hash {$ key}' –

+0

你們倆,非常感謝!這兩個解決方案正是我所需要的。 – romeroqj