【问题标题】:ref to a hash -> its member array -> this array's member's value. How to elegantly access and test?引用哈希 -> 其成员数组 -> 此数组的成员值。如何优雅地访问和测试?
【发布时间】:2016-06-16 19:13:58
【问题描述】:

我想使用类似的表达式

@{ %$hashref{'key_name'}[1]

%$hashref{'key_name}->[1]

获取 - 然后测试 - 我的哈希持有的数组(引用)的第二个(索引 = 1)成员作为其“key_name”的值。但是,我做不到。

这里的代码是正确的(它有效),但我希望将我标记的两行合并为一条高效、优雅的行。

foreach  my $tag  ('doit', 'source', 'dest' ) {
    my $exists = exists( $$thisSectionConfig{$tag}); 
    my @tempA = %$thisSectionConfig{$tag} ;          #this line
    my $non0len = (@tempA[1] =~ /\w+/ );             # and this line
    if ( !$exists || !$non0len) {
        print STDERR "No complete \"$tag\" ... etc ... \n";
        # program exit ...
    }

我知道你(一般的“你”)可以优雅地结合这两条线。有人能告诉我我该怎么做吗?

此代码测试配置文件的一部分,该部分已被 Config::Simple 读入 $thisSectionConfig 对哈希的引用。然后每个配置文件 key=value 对(我用 datadumper 查看)保存为两个成员数组:[0] 是键,[1] 是值。 $tag 是必须存在于此代码 sn-p 处理的配置文件部分中的配置设置。

感谢您的帮助。

【问题讨论】:

    标签: arrays perl hash reference


    【解决方案1】:

    您应该阅读有关Arrow operator(->) 的信息。我猜你想要这样的东西:

    foreach  my $tag  ('doit', 'source', 'dest') {
        if(exists $thisSectionConfig -> {$tag}){ 
            my $non0len = ($thisSectionConfig -> {$tag} -> [1] =~ /(\w+)/) ;         
        }            
        else {
            print STDERR "No complete \"$tag\" ... etc ... \n";
            # program exit ...
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多