mysql - Saving the output of a Perl SQL query to a hash instead of an array -
i'm trying add argument end of command line, run search through mysql database, , list results or nothing found. i'm trying saving query data both hashes , arrays (these exercises, i'm extremely new @ perl , scripting , trying learn). however, can't figure out how same thing hash. want sql query complete, , write output hash, not invoke while function. guidance appreciated.
#!/usr/bin/perl -w use warnings; use dbi; use getopt::std; &function1; &function2; if ($arrayvalue != 0) { print "no values found '$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 players_sport sport '$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; }; }
please see , read dbi documentation on selectall_hashref
. returns reference hash of reference hashes.
use syntax:
$dbh->selectall_hashref($statement, $key_field[, \%attri][, @bind_values])
so here example of what/how returned:
my $dbh = dbi->connect($dsn, $user, $pw) or die $dbi::errstr; $href = $dbh->selectall_hashref(q/select col1, col2, col3 table/, q/col1/);
your returned structure like:
{ value1 => { col1 => 'value1', col2 => 'value2', col3 => 'value3' } }
so follows accessing hash references:
my $href = $dbh->selectall_hashref( q/select player players_sport/, q/player/ ); # $_ value of player print "$_\n" (keys %$href);
you can access each hash record individually doing so:
$href->{$_}->{player}
Comments
Post a Comment