2013-05-10 53 views
2

我試圖在命令行末尾添加一個參數,通過MySQL數據庫運行搜索,然後列出結果或說什麼都沒找到。我試圖通過將查詢數據保存爲哈希和數組來做到這些(這些是練習,我對PERL非常陌生,腳本和嘗試學習)。但是,我無法弄清楚如何使用散列做同樣的事情。我希望SQL查詢完成,然後將輸出寫入散列,以免調用While函數。任何指導將不勝感激。將Perl SQL查詢的輸出保存爲散列而不是數組

#!/usr/bin/perl -w 
use warnings; 
use DBI; 
use Getopt::Std; 

&function1; 
&function2; 

if ($arrayvalue != 0) { 
    print "No values found for '$search'"."\n"}; 

sub function1 { 

getopt('s:'); 
$dbh = DBI->connect("dbi:mysql:dbname=database", "root", "password") 
    or die $DBI::errstr; 

$search = $opt_s; 
$sql = $dbh->selectall_arrayref(SELECT Player from Players_Sport where Sport like '$search'") 
or die $DBI::errstr; 
@array = map { $_->[0] } @$sql; 
$dbh->disconnect 
    or warn "Disconnection failed": $DBI::errstr\n"; 

} 

sub function2 { 

@array; 
$arrayvalue=(); 
print join("\n", @array, "\n"); 
if(scalar (@array) == 0) { 
    $arrayvalue = -1 
} 
    else {$arrayvalue = 0; 
}; 

} 

回答

2

請參閱並閱讀關於selectall_hashref的DBI文檔。它返回對散列引用散列的引用。

使用語法

$dbh->selectall_hashref($statement, $key_field[, \%attri][, @bind_values]) 

因此,這裏是什麼/如何將返回一個例子:

my $dbh = DBI->connect($dsn, $user, $pw) or die $DBI::errstr; 

my $href = $dbh->selectall_hashref(q/SELECT col1, col2, col3 
            FROM table/, q/col1/); 

你返回的結構將類似於:

{ 
    value1 => { 
     col1 => 'value1', 
     col2 => 'value2', 
     col3 => 'value3' 
    } 
} 

所以你可以做如下的訪問哈希引用NCES:

my $href = $dbh->selectall_hashref(q/SELECT Player FROM 
             Players_Sport/, q/Player/); 

# $_ is the value of Player 
print "$_\n" for (keys %$href); 

你可以簡單地做作爲這樣單獨訪問每個哈希記錄:

$href->{$_}->{Player} 
+0

完美奏效,謝謝。 – user2361820 2013-05-10 04:54:46

1

documentation惡癖:

$sql = $dbh->selectall_hashef("SELECT Player from Players_Sport where Sport like ?", 'Players_Sport_pkey', $sport_like_value); 
my %hash_of_sql = %{$sql};