代码之家  ›  专栏  ›  技术社区  ›  Uri London

Perl方法返回“hashref”是什么意思?

  •  8
  • Uri London  · 技术社区  · 16 年前

    我正在尝试解密一个我不熟悉的Perl代码,它与HashRef有关。

    use Amazon::S3;
    my $s3 = Amazon::S3->new( ... );
    my $response = $s3->buckets;
    

    文档(此处)sais,关于s3->水桶:

    Returns undef on error, else HASHREF of results
    

    for $b in ( @ { $response->{buckets} } ) {
        print "bucket: " . $b->bucket . "\n";
    }
    

    我对第一行的每个接线员都感到困惑。

    你到底是什么类型的 $response $respone->{bucket} 看起来像是 for 是一个数组,但我不懂这个语法: @{ ... }

    3 回复  |  直到 16 年前
        1
  •  10
  •   friedo    16 年前

    让我们一件一件地看一下。

    $s3 是你的S3对象。 $s3->buckets 呼叫 buckets $response . 正如文档所说,结果是一个散列引用;引用是指向另一个值的标量。如果你熟悉指针,想法是一样的。

    如果我们有一个简单的杂烩 %response ,我们可以到达 水桶 $response{buckets} -> )抓住钥匙 $response->{buckets} .

    但我们还没做完。 是 它本身 引用,在本例中是数组引用。这里我们看到了另一种形式的解引用。如果我们只想得到引用数组中的一个项,比如 $response->{buckets}[0] ,例如。但是我们想要整个名单,所以我们用 @ 运算符取消对整个数组的引用。由于数组引用包含在复杂结构中,因此我们使用卷曲来包含包含引用的表达式。所以呢 @{ $response->{buckets} } 把数组给我们。

    在一份声明中做了很多。

    有关引用的更多信息,请参见以下内容,这可能是Perl中最难学习的主题之一:

        2
  •  4
  •   Charles    16 年前

    欢迎来到Perl参考的世界!你会找到 reference tutorial 非常方便。

    @{...} 获取标量值并尝试将其反引用到数组中。还有 %{...} ,尝试将引用反引用为哈希。卷发是可选的,所以你也可以写 @$reference 或 %$reference 得到同样的效果。当引用位于散列或数组中时,有些人会发现它们在视觉上很有用,这里就是这样。

    为了帮助您更好地理解数据结构,请尝试使用类似data::Dumper的方法。

    use Data::Dumper;
    print Dumper $response;
    print Dumper $response->{buckets};
    # The docs say that buckets is a hashref.  It also happens that
    # you can coerce a hash into an array.  Let's treat it as a hash
    # and see what's inside it, manually.  The Dumper call above should
    # have already provided the structure to you, though.
    foreach my $k (keys %{$response->{buckets}}) {
        print "$k => " . Dumper $response->{buckets}->{$k}
    }
    
        3
  •  -1
  •   asjo    16 年前

    可以使用ref()函数检查变量的类型。

    @{ ... } 表示“取消引用标量…”。。。作为数组”。所以如果你这样做:我的$aref=['a','b'];访问@{$aref}将产生数组('a','b')。

    相似的%{…}用于哈希引用。