【问题标题】:syntax for accessing hash param in hash of hashes when using foreach使用 foreach 时访问哈希哈希中的哈希参数的语法
【发布时间】:2013-07-27 06:31:53
【问题描述】:

我有这个哈希值,我正在尝试用每个哈希值填充一个选择框。无论如何,我无法获取我的内部哈希变量。我能够在我的选择中生成正确数量的选项,但我目前只能设置每个选择选项的值参数。

这是我的哈希:

my $export_types = { a      => {label => "Foo", ext => ".js"},
                     b      => {label => "Bar", ext => ".gz"}};

这是我迄今为止为我的 foreach 尝试过的:

my $select = "<select id='fancy'>";
foreach my $key (sort keys %{$export_types})
{
    $select .= "<option value='$key' ";
    if($saved_value eq $key || (!$saved_value && $key eq "a"))
    {
        $select .="selected='selected'";
    }
    $select .= ">".$export_types{$key}{label}."</option>";
}
$select .= "</select>";

显然我访问标签属性错误。对于该特定行,我也尝试过:

$select .= ">".$export_types{$key}->{label}."</option>";

但这也无济于事。我确定我错过了一些简单的东西。

感谢您的帮助:)

【问题讨论】:

    标签: html perl hash foreach


    【解决方案1】:

    表达式

    $export_types{$key}{label}
    

    假设有一个哈希%export_types。不是这种情况。如果你有一个use strict 在范围内,你就会被告知这个事实。

    因为$export_types 是一个散列引用,我们必须在使用下标操作符访问某个值之前取消对它的引用。要么

    $export_types->{$key}{label}
    

    $$export_types{$key}{label}
    

    (我更喜欢前者)。

    【讨论】:

      猜你喜欢
      • 2014-05-06
      • 2013-03-22
      • 2013-06-06
      • 2012-05-28
      • 1970-01-01
      • 2011-05-27
      • 2019-03-26
      • 2012-08-17
      • 1970-01-01
      相关资源
      最近更新 更多