2012-03-05 41 views
1

MongoDB中我寫了一個腳本將項目插入mongodb插入用Perl

#!/usr/bin/perl 
use strict; 
use warnings; 
use MongoDB; 
use Data::Dumper; 

my $hostname = "localhost"; 
my $port = 27017; 

my $conn = MongoDB::Connection->new("host" => "$hostname", 
            "port" => $port); 
my $db = $conn->test; 
my $user_stats = $db->test_stats; 

# Insert line 
$user_stats->insert({'user_id' => 123, 
        'pointA'=> 12, 
        'pointB' => 13, 
        'total' => 25, }); 

my $myStr = $user_stats->find_one(); 
print Dumper($myStr); 

代碼工作做好。 然而,當我改變insert line

my $a = "{'user_id' => 123, 
      'pointA' => 12, 
      'pointB' => 13, 
      'total' => 25}"; 

$user_stats->insert($a); 

它不工作還給錯誤:not a reference at /usr/local/lib/perl5/site_perl/5.12.3/sun4-solaris/MongoDB/Collection.pm line 296.

+1

好吧,不要將工作代碼更改爲非工作代碼。爲什麼你想讓'$ a'成爲一個字符串? – cjm 2012-03-05 07:25:53

回答

5

insert method on MongoDB::Collection預計哈希REF:

insert ($object, $options?)

Inserts the given $object into the database and returns it's id value. $object can be a hash reference, a reference to an array with an even number of elements, or a Tie::IxHash .

所以,通常的做法是使用哈希引用和你的$a是一個字符串,而不是哈希引用。其他選項是可以容易地「投射」到散列引用(即,其形式爲[key, value, key, value, ...])或Tie::IxHash(這是維持順序的散列)的陣列引用。你的$a字符串也不是其中之一。

+0

謝謝。 Tie :: IxHash確實解決了這個問題。 – conandor 2012-03-05 07:59:20