Perl哈希无法正常工作 [英] Perl hashes don't work as expected

查看:111
本文介绍了Perl哈希无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/perl

sub f { {
  a => 1,
  b => 2
} }

sub g { {
  %{f()},
  c => 3,
  d => 4,
} }

use Data::Dumper;
print Dumper g();

上面的代码输出

$VAR1 = 'a';
$VAR2 = 1;
$VAR3 = 'b';
$VAR4 = 2;
$VAR5 = 'c';
$VAR6 = 3;
$VAR7 = 'd';
$VAR8 = 4;

尽管我认为它应该输出

$VAR1 = {
          'a' => 1,
          'c' => 3,
          'b' => 2,
          'd' => 4
        };

我的误会是什么?

推荐答案

问题是在Perl中一对花括号不明确,可能是块或匿名哈希

The problem is that a pair of braces is ambiguous in Perl, and may be either a block or an anonymous hash

由于g中的哈希内容(请使用更好的名称),perl假定您正在编写代码块,它只是标量值的列表

Because of the contents of the hash in your g (please use better names) perl has assumed that you are writing a code block, which is just a list of scalar values

像这样使它更加明确,您的代码将按预期运行

Make it more explicit like this and your code will function as you expect

use strict;
use warnings 'all';

sub foo {
    {
        a => 1,
        b => 2,
    }
}

sub bar {
    my $href = {
        %{ foo() },
        c => 3,
        d => 4,
    }
}

use Data::Dump;
dd bar();

输出

{ a => 1, b => 2, c => 3, d => 4 }

这篇关于Perl哈希无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆