Reputation: 3707
I want to query a list of nickname from a text file.
#!/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;
It seem it fail to recognise variable $line
at the line my $statsResult = $user_stats->find( { msisdn => '$line' } );
It works if I replace $line
with a string like mynickname
. The print statement in previously works ok.
Am I missing something here?
Upvotes: 1
Views: 732
Reputation: 8986
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.
Upvotes: 4