1

我想从文本文件中查询昵称列表。

#!/usr/bin/perl    
use strict;
use warnings;
use MongoDB;

# Open file
print "--> Read file\n";
open( INPUT, "<userlist.txt" ) or die "Could not open the file: $!\n";
print "--> Read INPUT OK\n";
open( OUTPUT, ">>outfile.txt" ) or die "Could not open the file: $!\n";
print "--> Read OUTPUT OK\n";

# MongoDB parameter
my $mongoHost = localhost;
my $mongoPort = 12345;

my $conn = MongoDB::Connection->new( "host" => "$mongoHost", "port" => $mongoPort );    # Open connection
my $db = $conn->mylist;                                                                 # Connect to database
my $user_stats = $db->user_stats;                                                    # Choose a collection
print "--> Connect to MongoDB\n";

# Read through line
foreach my $line ( <INPUT> ) {
    # Extract content
    chomp( $line );   # Remove newline
    print "$line\n";

    my $statsResult = $user_stats->find( { nickname => '$line' } );
    while ( my $obj = $statsResult->next ) {
        print $obj->{ "nickname" } . ";";
        print $obj->{ "total" } . "\n";
    }
}
close( OUTPUT );
close( INPUT );

print "--> End of Code\n";
exit 0;

似乎无法识别$line该行的变量my $statsResult = $user_stats->find( { msisdn => '$line' } ); 如果我$line用类似的字符串替换它就可以了mynickname. 以前的打印语句可以正常工作。

我在这里错过了什么吗?

4

1 回答 1

4

You're using single quotes in your line

my $statsResult = $user_stats->find( { nickname => '$line' } );

Meaning that the database is being searched for the string $line, not the contents of the variable. Remove the single quotes and you should be fine.

Also, here's a nice tutorial on the different forms of quoting in Perl, which explains why single quotes are different from double quotes, what qq means, etc.

于 2012-04-25T15:37:36.367 回答