How to pass a a string variable as “query” for get Manager call?

可紊 提交于 2019-12-12 05:14:47

问题


I'm trying to make this simple call:

DataB::testTable::Manager->get_testTable( query => [ id => $id, name => $name ] )

which works perfectly fine. But is it possible to pass a variable for the query. Something like:

$query = "id => $id , name => $name";
DataB::testTable::Manager->get_testTable( query => [ $query ] );

or something similar.


回答1:


Strings and complex data structures are completely different things.

Strings are a sequence of codepoints/graphemes/bytes (depends how you're looking). Strings are dumb. Strings are not good at containing complex and/or hierarchical data. (Point in case: XML is pure pain)

However, you can put any Perl data structure into a scalar variable, using references. Square brackets create a reference to an anonymous array.

These groups of lines are equivalent except for the fact that a variable name is introduced:

DataB::testTable::Manager->get_testTable( query   => [ id => $id, name => $name ] );

my @query = (id => $id, name => $name);
DataB::testTable::Manager->get_testTable(query => \@query); # the "\" takes a reference to a value

my @query = (id => $id, name => $name);
DataB::testTable::Manager->get_testTable(query => [@query]); # using "[]" to make the arrayref. The reference points to a copy of @query.

# this solution is probably best:
my $query = [ id => $id, name => $name ]; # "[]" makes an arrayref
DataB::testTable::Manager->get_testTable(query => $query);

Using references to data structures is better than using strings.

(You could interpret a string as Perl source code via eval. This is extremely powerful, but not everything stringifies to a form that can be eval'd into an equivalent data structure. Don't use string-eval, except for well thought out metaprogramming.)

For further info on references and complex data structures, perlref, perlreftut and perldsc might be interesting.



来源:https://stackoverflow.com/questions/14678683/how-to-pass-a-a-string-variable-as-query-for-get-manager-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!