2

我正在尝试在命令行末尾添加一个参数,通过 MySQL 数据库运行该搜索,然后列出结果或说什么也没找到。我试图通过将查询数据保存为散列和数组来做到这一点(这些是练习,我对 PERL 和脚本非常陌生,并试图学习)。但是,我不知道如何用哈希做同样的事情。我确实希望 SQL 查询完成,然后将输出写入哈希,以免调用 While 函数。任何指导将不胜感激。

#!/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;
};

}
4

2 回答 2

3

请参阅并阅读 DBI 文档selectall_hashref。它返回对哈希引用的哈希的引用。

使用语法

$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'
  }
}

因此,您可以执行以下操作来访问您的哈希引用:

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} 
于 2013-05-10T03:02:00.620 回答
1

文档中抄袭:

$sql = $dbh->selectall_hashef("SELECT Player from Players_Sport where Sport like ?", 'Players_Sport_pkey', $sport_like_value);
my %hash_of_sql = %{$sql};
于 2013-05-10T03:02:49.460 回答