开发者

How to escape '$' character in perl?

开发者 https://www.devze.com 2023-04-11 19:19 出处:网络
I am trying to execute a MongoDB query as below : $Coll开发者_如何学Goection1->update({\"_id\":\\$id}, { \\$set: {\"Title\":$title} }, false );

I am trying to execute a MongoDB query as below :

$Coll开发者_如何学Goection1->update({"_id":\$id}, { \$set: {"Title":$title} }, false );  

But I get below error-

Global symbol "$set" requires explicit package name at file.pl line xx.

As per MongoDB documentation, \$set is supposed to work just fine. What could be wrong here?


There are a couple of problems.

  • A Perl hash is comma separated. It is not JSON or JavaScript. Don't use a :.
  • You can avoid quoting key names if you use a fat comma (=>)
  • That isn't the case if you use really odd characters. Use a non-interpolated string if you want a $ in the key name.

This:

$Collection1->update({"_id" => \$id}, { '$set' => { Title => $title} }, false );  


You can use the simple single quotes, which in Perl will NOT interpolate the value inside. Then your '$' will be passed as just part of the string instead of trying to interpolate a value for a variable.

$Collection1->update({'_id' => $id}, { '$set' => {'Title' => $title} }, false );  

Note in the example above I also changed your double quotes around the field names to be single quotes also. It's good practice in Perl to use single quotes when you mean a string literal, and double quotes when you want to replace with the value of a variable. Also, you don't want (or need) to escape the '$' in front of the '$id' as, you do want the id variable to be replaced in the update call.

the "qw()" operator Paul showed does the same thing. See "Quote and Quote‐like Operators" in the perldoc perlop section.

edited answer to reflect other comments about the improper hash notations.


Take advantage of the different quoting mechanisms in Perl.

For example, quote words just says "treat everything inside literally". I've used parentheses as my delimiters here, but another very cool thing about qw is that you are free to use appropriate delimiters for your situation.

$Collection1->update({"_id":\$id}, { qw($set): {"Title":$title} }, false );  


This is nothing to do with quoting. The message from perl is telling you that it is finding the symbol $set (so it is correctly interpreting the sigil) but that there is no such symbol in scope.

Probably you have 'use strict' on, and have failed to declare $set with 'my' (or 'our').

0

精彩评论

暂无评论...
验证码 换一张
取 消