【问题标题】:How can I work with multiple values using ->?如何使用 -> 处理多个值?
【发布时间】:2014-09-23 20:02:23
【问题描述】:

我是 Perl 新手,对现有脚本做了一些更改,但我不确定这在 Perl 中是否正确使用。在 C# 中我们做的事情不同,那么下面的代码示例是否正确?

$group->{$type}{class} = 1;

我添加的代码是

 $group->{$type}{class} = 1;
 $group->{$name}{port} = 1;

这是对的吗? $group 可以同时指向类型和名称。我用一个示例 Perl 脚本进行了尝试,它似乎正确设置并返回了 '1'。但我不确定我是否应该这样做。

【问题讨论】:

  • 提供更多细节和一个简单的例子来说明你想要实现的目标。

标签: perl


【解决方案1】:

是的,这看起来是正确的。您正在构建一个复杂的数据结构,特别是 hash of hashes (HoH)。 group 哈希有两个键,$type$name$type 子哈希有一个键,class$name 子哈希有一个键,port。如果你把它扔掉或一次性声明它,它看起来大概是这样的:

$group = {
  $type => {
    class => 1
  },
  $name => {
    port => 1
  }
}

当然,$type$name 将评估它们设置的任何值。它不会将引用存储在哈希中。

【讨论】:

    【解决方案2】:

    嗯...这是perl。如果有效,那就对了。但是,对于你的问题。在您的代码中,$group 是对哈希的引用(在 c# 中可能称为 dictionary)。我想你可能正在寻找这个:

    my $group={}; # make the ref
    my @types = ('hot','cold','warm');   # make some types
    my @names = ('sink','bath','drain'); # and some names
    
    foreach my $type (@types){
        $group->{'type'}->{$type}++; # add a new $type to the "type" sub hash
    }
    
    foreach my $name (@names){
        $group->{'name'}->{$name}++; # add a new $nameto the "name" sub hash
    }
    

    现在循环浏览这些类型,例如:

    foreach my $typeKey (keys %{$group->{'type'}}){
        print "type is " . $typeKey; # this is from the @types array
        print ", value = " . $group->{'type'}->{$typeKey}; # this would be 1
    }
    

    【讨论】:

    • 感谢您的澄清。我每天都在学习新东西:)
    猜你喜欢
    • 2017-01-22
    • 2018-02-23
    • 2018-07-18
    • 2019-03-05
    • 2015-05-29
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    相关资源
    最近更新 更多