如何在 Perl 中的哈希引用中引用标量?
简单的问题:
我如何在一行上执行此操作:
my $foo = $bar->{baz};
fizz(\$foo);
我尝试过 \$bar->{baz}、\${$bar->{baz}} 以及许多其他方法。 这可能吗?
-fREW
更新:好的,哈希引用来自 DBI,我将标量引用传递到模板工具包中。 我想,现在我更仔细地观察,这个问题与 TT 是如何做到这一切有关的。 实际上我想说:
$template->process(\$row->{body}, $data);
但是 TT 不是这样工作的,TT 采用标量引用并将数据放在那里,所以我必须这样做:
$template->process(\$row->{body}, $shopdata, \$row->{data});
无论如何,感谢您的帮助。 我至少只会有一份参考资料,而不是两份。
Simple question:
How do I do this on one line:
my $foo = $bar->{baz};
fizz(\$foo);
I've tried \$bar->{baz}, \${$bar->{baz}}, and numerous others. Is this even possible?
-fREW
Update: Ok, the hashref is coming from DBI and I am passing the scalar ref into template toolkit. I guess now that I look more closely the issue is something to do with how TT does all of this. Effectively I want to say:
$template->process(\$row->{body}, $data);
But TT doesn't work that way, TT takes a scalar ref and puts the data there, so I'd have to do this:
$template->process(\$row->{body}, $shopdata, \$row->{data});
Anyway, thanks for the help. I'll at least only have one reference instead of two.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
应该管用。
例如:
为了回答 OP 中的更新,您可以这样做:
这与 \@array 不同,后者会创建对数组的一个引用。 上面将分发参考文献并列出两个参考文献。
should work.
E.g.:
In answer to the update in the OP, you can do:
This is not the same as \@array, which would create one reference to an array. The above will distribute the reference and make a list of two references.
\$bar->{baz} 似乎对我有用:
\$bar->{baz} seems to do the trick for me:
您没有显示 %bar 和 fizz() 是如何设置的,所以我像这样设置它们:
然后,这两个工作,您的原始:
以及您所说的尝试过的变体之一:
您能显示给出的错误吗你?
You didn't show how %bar and fizz() were setup, so I set them up like this:
Then, both of these work, your orignal:
and one of the variants you said you tried:
Can you show the error that's giving you?
我什至不确定你在做什么。
您还应该在 baz 周围加上引号。
现在让我们考虑一下,您将一个标量分配给第一行中的标量,然后第二行应该可以工作。
然而我真的不知道这是否是你在这里尝试的,并且它在 Perl 中没有真正的意义。
在其他语言中经常使用引用来
现在标量通常不需要第一个,而且无论如何 Perl 是一种脚本语言,所以如果您真的关心编写 C 的速度。
第二个在 Perl 中不需要,因为您可以很容易地返回列表和对匿名哈希的引用。
你看过“man perlref”吗?
I am not even sure what you are doing.
You also should put quotes around baz.
Now let's consider that you assign a scalar to the scalar in the first line then the second line should work.
However I don't really know if this is what you are trying here and it does not really make sense in Perl.
Using references is often used in other languages to
Now the first is usually not needed with scalars and anyway Perl is a script language so if you are really concerned about speed write C.
The second is not needed in Perl as you can return lists and references to anonymous hashes quite easy.
Have you looked at "man perlref"?