4

我经常将很多数据保存到一个hash var中,或者根据条件获取数据。这不方便,所以我想要一个模块,使用 SQL 作为 NoSQL 访问数据。我找到了DBD::RAM,但是有更小的模块吗?

例如:像 MySQL 表这样的哈希数据:

{
   "table": "company",
   "rows" : [
       {
         "name": "baidu",
         "location": "China"
       },
       {
         "name": "taobao",
         "location": "China"
       }
    ]
}

一般来说,插入这样的记录:

my %new_row = (name=>xxx, location=>yyy);
push (@{$hash->{rows}}, \%new_row);

如果我这样做,会有很多散列变量,所以我想更像这样:

$handle->insert('insert into company values("xxx", "yyy")');

my ($name, $location) = $handle->select_unqiue_record(<<"_EOC_";
    select name, location from company where name="baidu"
_EOC_);
4

2 回答 2

2

我推荐https://metacpan.org/module/DBIx::DataModel

一旦你设置了一个描述你的目标表的模式——你可以通过逆向工程自动完成——你可以像这样直接插入你的哈希:

my $table = $schema->table($table_name);
my $id = $table->insert($hash_ref);

实际上,您可以将 DBIx::DataModel 传递给 hash_refs 数组(根据您的问题),它会为您插入其中的每一个。请参阅以下文档: https ://metacpan.org/module/DBIx::DataModel#Insert

于 2013-07-02T04:29:11.757 回答
0

If I understand you correctly, you're storing data in complex structures that you find hard to manipulate. The reason you're asking about NoSQL type of stuff is that you want an easy way to store and manipulate your data.

It's then time to roll up the sleeves and learn Object Oriented Perl.

Creating Perl objects is a good way to handle your complex data structure, and it's really not all that hard to learn. I normally write classes on the fly and just declare them at the end of my program.

This is the data structure you had in your initial post as a Company class:

package Company;

sub new {
    my $class    = shift;
    my $name     = shift;
    my $location = shift;

    my $self = {};
    bless $self, $class;

    $self->Name($name);
    $self->Location($location);
    return $self;
}

sub Name {
    my $self     = shift;
    my $name     = shift;

    if ( defined $name ) {
        $self->{NAME} = $name;
    }
    return $self->{NAME};
}

sub Location {
    my $self      = shift;
    my $location  = shift;

    if ( defined $location ) {
        $self->{LOCATION} = $location;
    }
    return $self->{$LOCATION};
}

That's all there is to it. Now I can easily create and manipulate my companies without worrying about manipulating hashes of hashes, or trying to remember exactly how I structured my data:

# Read in all of the companies from $company_file into @company_list

open my $company_fh, "<", $company_file;
my @company_list;
while ( my $line = <$company_fh> ) {
    chomp $line;
    my ($name, $location) = split /:/, $line;
    my $company = Company->new( $name, $location );
    push @company_list, $company;
}
close $company_fh;

Later on, I can manipulate my companies like this:

#Print out all Chinese Companies
for my $company ( @company_list ) {
    if ( $company->Location eq "China" ) {
        say $company->Name . " is located in China.";
    }
}
于 2013-07-03T00:51:15.447 回答