Why doesn't Perl support interpolation of hashes in double quotes?

耗尽温柔 提交于 2019-11-30 03:28:22

问题


#!/usr/bin/perl
use warnings;

my %hash=("no1"=>1, 
        "no2"=>2,
      );

print %hash; #Prints no11no22
print "%hash"; #Prints %hash

Why doesn't Perl support interpolation of a hash within double quotes? It supports interpolation for scalars ($), arrays (@) then why not for hashes (%)?


回答1:


How should a hash stringify? Scalars are obvious and arrays too. But what should a hash be? How useful will such a stringification be? Is it more or less useful than being able to use a % character unescaped in an interpolating string? Is it worth the amount of work it will take to fix all of the code that uses % in interpolated strings today?

If you can come up with good answers to these questions, then I am sure P5P would be willing to listen to them.




回答2:


To quote Nathan Torkington: "The big problem is that % is heavily used in double-quoted strings with printf." More information is here.




回答3:


Not really an answer to the "why", but I thought I would point out various answers to the "how".

One could, of course, try:

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

my %hash = (
    "no1" => 1,
    "no2" => 2,
);

print "@{[ %hash ]}\n";

But, I don't know what use that would be.

If you want to dump the contents of a hash or any other complicated data structure, use Data::Dumper or YAML or JSON depending on your use case.



来源:https://stackoverflow.com/questions/6731291/why-doesnt-perl-support-interpolation-of-hashes-in-double-quotes

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