如何从模块perl返回哈希

时间:2012-06-28 13:33:35

标签: perl select module dbi subroutine

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

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和哈希引用但从来没有哈希的实际值。任何帮助都会非常感谢!

2 个答案:

答案 0 :(得分: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,永远不会被调用。

答案 1 :(得分: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->{$_}";
}