0

好的,所以这个问题困扰了我一段时间。我正在运行一个连接到数据库并从查询中返回值的模块。我有一个脚本调用模块并尝试从模块的子例程返回值。但是由于代码比文字更好,这就是我所拥有的:

sub selectCustomerName ($code){
    connectDB() or die "Failed in subroutine";
    #Selects customer name from customer table where code is $code
    my $selectName = "SELECT * FROM customers WHERE code = ?";
    my $sth = $dbh->prepare($selectName);
    $sth->execute($code);
my $hash = $sth->fetchrow_hashref;
$hash->{customer_name} = $name;
return $name;
$sth ->finish();
$dbh->disconnect();
}

这是我的模块,这是我的脚本:

#!/usr/bin/perl
require Connect;
use warnings;
my $dbh = Connect::connectDB();
my $results = Connect::selectCustomerName('38d');
print $results;

从大量的混乱和切换变量中,我得到了打印 0 和哈希引用,但从来没有打印出哈希的实际值。任何帮助都会非常感谢!

4

2 回答 2

1

有一些错误。试试这个:

use strict; use warnings; # never forget this 2 pragmas
use Data::Dumper; # print what's inside data structures or object

sub selectCustomerName {
    my $code = shift; # or my ($code) = @_; 

    connectDB() or die "Failed in subroutine";
    #Selects customer name from customer table where code is $code
    my $selectName = "SELECT * FROM customers WHERE code = ?";
    my $sth = $dbh->prepare($selectName);
    $sth->execute($code);
    my $hash = $sth->fetchrow_hashref;
    print Dumper $hash;
    $name = $hash->{customer_name};
    $sth ->finish();
    $dbh->disconnect();
    return $name;
}
  • 如果你把finish()&放在disconnect()之后return,它们将永远不会被调用。
于 2012-06-28T13:38:45.237 回答
0

查看您实际拥有的最简单的方法可能是使用Data::Dumper

#!/usr/bin/perl

use strict;
use warnings;

require Connect;
use Data::Dumper;

my $dbh = Connect::connectDB();
my $results = Connect::selectCustomerName('38d');
print Dumper $results;

但是,如果您有一个哈希引用,那么您可以%{$hash_ref}使用它来尊重它,并像使用任何其他哈希一样使用它。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

require Connect;

my $dbh = Connect::connectDB();
my $results = Connect::selectCustomerName('38d');

foreach (keys %{$results}) {
  say "Key: $_, Value: $results->{$_}";
}
于 2012-06-28T13:56:39.943 回答