Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing a hash from a subroutine

Status
Not open for further replies.

netman4u

Technical User
Mar 16, 2005
176
US
I have a subroutine that queries a DB loads and loads a hash with the results:

Code:
sub VistaQuery {
my $vendor;
my $ip;
my %_sub_db_results;
my $data_source = "dbi:Oracle:binvdp01";
  my $dbh = DBI->connect($data_source, $orauser, $orapass)
      or die "Can't connect to $data_source: $DBI::errstr";

  my $sth = $dbh->prepare( q{select T1.SVALUE, T2.SVALUE from twtpropvalues T1, twtpropvalues T2 where
								T1.PROPID=(select ID from twtproperties where WID='00000000000000000000000000000001')
								and T2.PROPID=(select ID from twtproperties where 
								WID='72B1577C795AB24888F4462B18D8F42D') and T1.INSID=T2.INSID}
  ) or die "Can't prepare statement: $DBI::errstr";

  my $rc = $sth->execute
      or die "Can't execute statement: $DBI::errstr";

  print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
  print "Field names: @{ $sth->{NAME} }\n";

  while (($ip, $vendor) = $sth->fetchrow_array) {
	  $sub_db_results{$ip} = $vendor; 
  }
#
# check for problems which may have terminated the fetch early
#
  die $sth->errstr if $sth->err;

  $dbh->disconnect;

[b]  return \%sub_db_results;[/b]

}# End sub VistaQuery

My question is how do I dereference it in my program into the hash %db_results?

Code:
my %db_results = VistaQuery??

Thanks,

Nick



If at first you don't succeed, don't try skydiving.
 
First of all:

Code:
my %_sub_db_results;

When you declare the hash there's an underscore at the beginning, but later you refer to it as just $sub_db_results.

Secondly:

Code:
return \%sub_db_results;

That's returning a reference to a hash. The difference between a hash and a hashref is an arrow:

Code:
$hash{key}; # normal hash
$hash->{key}; # hash reference

Try this:

Code:
return (%sub_db_results);

#...#

my %db_results = VistaQuery;
 
unless that is a really big hash there is probably no need to return it as a reference to the hash anway. Just return the hash like Kirsle showed above:

return (%sub_db_results);



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top