2011-07-19 32 views
1

如何從fetchrow_hashref中獲取另一列?perl - 幫助通過dbi調用獲取另一列

例如,我原來的子例程返回一個值。

sub get_val 
    { 
     undef $/; 
     open (my $FH, "< tst.sql") or die "error can't open this file $!"; 
     my $sth= $dbh->prepare(<$FH>) || 
      die ("Cannot connect to the database: ".$DBI::errstr."\n"); 
     $sth->execute; 
     close $FH; 
     my $row = $sth->fetchrow_hashref; 
     $sth->finish; 
     return $row->{COL1}; 
     print $row; 
    } 

我改變了我的SQL,所以現在我就在2個值的回報和希望獲取COL2

COL1  COL2 
------ ------- 
1  A 

這裏就是我的get_val撥打:

my $dbh = DBI->connect(
     $abc{oracle_dbi_connect}, 
     $abc{usr}, 
     $abc{pw}, 
     {AutoCommit => 0,RaiseError => 0, PrintError => 0}) || die ("Cannot connect to the database: ".$DBI::errstr."\n"); 
my $val = get_val(); 
$dbh->disconnect(); 

我可能會然後想要將COL2結果分配給新的$ val2?

回答

3

我敢肯定得到COL2就像使用$row->{COL2}而不是$row->{COL1}(就像你在你的代碼中一樣)那麼簡單。所以,讓你的get_val函數返回兩個值:

return @$row{'COL1', 'COL2'}; 

,並在調用函數:

my ($val, $val2) = get_val(); 
+0

謝謝。現在效果很好:-) – jdamae