为什么我会在Perl中返回散列或散列引用? [英] Why would I return a hash or a hash reference in Perl?

查看:116
本文介绍了为什么我会在Perl中返回散列或散列引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完成下面的最有效的方法是什么? (我知道他们完成了同样的事情,但大多数人会如何在三者之间做到这一点,而为什么?)

文件a.pl



What is the most effective way of accomplishing the below? (I know they accomplish the same thing, but how would most people do this between the three, and why?)

my %hash = build_hash();
# Do stuff with hash using $hash{$key}
sub build_hash
{
    # Build some hash
    my %hash = ();
    my @k = qw(hi bi no th xc ul 8e r);
    for ( @k )
    {
        $hash{$k} = 1;
    }

    # Does this return a copy of the hash??
    return %hash;
}



文件b.pl



File b.pl

my $hashref = build_hash();
# Do stuff with hash using $hashref->{$key}
sub build_hash
{
    # Build some hash
    my %hash = ();
    my @k = qw(hi bi no th xc ul 8e r);
    for ( @k )
    {
        $hash{$k} = 1;
    }

    # Just return a reference (smaller than making a copy?)
    return \%hash;
}



文件c.pl



File c.pl

my %hash = %{build_hash()};
# Do stuff with hash using $hash{$key}
# It is better, because now we don't have to dereference our hashref each time using ->?

sub build_hash
{
    # Build some hash
    my %hash = ();
    my @k = qw(hi bi no th xc ul 8e r);
    for ( @k )
    {
        $hash{$k} = 1;
    }

    return \%hash;
}


推荐答案

有两个原因。其一,由于没有副本,所以它使用少量内存。二,它可以让你这样做,如果你只需要一块散列。

I prefer returning a hash ref for two reasons. One, it uses a bit less memory since there's no copy. Two, it lets you do this if you just need one piece of the hash.

my $value = build_hash()->{$key};

学会喜欢哈希引用,一旦开始使用对象,您将会看到它们很多。

Learn to love hash references, you're going to be seeing them a lot once you start using objects.

这篇关于为什么我会在Perl中返回散列或散列引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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