Program Tip

Perl에서 해시 참조와 해시 참조의 차이점은 무엇입니까?

programtip 2020. 11. 27. 21:11
반응형

Perl에서 해시 참조와 해시 참조의 차이점은 무엇입니까?


Perl의 해시를 제대로 이해하고 싶습니다. 저는 꽤 오랫동안 Perl을 간헐적으로 사용해야했고 대부분 필요할 때마다 텍스트 처리와 관련이 있습니다.

그리고 매번 해시를 처리해야 할 때마다 엉망이됩니다. 해시에 대한 구문이 매우 복잡하다는 것을 알았습니다.

해시 및 해시 참조, 차이점, 필요할 때 등에 대한 좋은 설명은 많은 도움이 될 것입니다.


간단한 해시는 배열에 가깝습니다. 초기화도 비슷해 보입니다. 먼저 어레이 :

@last_name = (
  "Ward",   "Cleaver",
  "Fred",   "Flintstone",
  "Archie", "Bunker"
);

이제 해시 (일명 연관 배열)로 동일한 정보를 표현해 보겠습니다.

%last_name = (
  "Ward",   "Cleaver",
  "Fred",   "Flintstone",
  "Archie", "Bunker"
);

이름은 같지만 배열 @last_name과 해시 %last_name는 완전히 독립적입니다.

배열을 사용하여 Archie의 성을 알고 싶다면 선형 검색을 수행해야합니다.

my $lname;
for (my $i = 0; $i < @last_name; $i += 2) {
  $lname = $last_name[$i+1] if $last_name[$i] eq "Archie";
}
print "Archie $lname\n";

해시를 사용하면 구문 적으로 훨씬 더 직접적입니다.

print "Archie $last_name{Archie}\n";

약간 더 풍부한 구조로 정보를 표현하고 싶다고 가정 해 보겠습니다.

  • Cleaver (성)
    • Ward (이름)
    • June (배우자 이름)
  • 플린트 스톤
    • 프레드
    • Wilma
  • 벙커
    • 아치
    • 에디스

참조가 나오기 전에는 플랫 키-값 해시는 우리가 할 수있는 최선 이었지만 참조는

my %personal_info = (
    "Cleaver", {
        "FIRST",  "Ward",
        "SPOUSE", "June",
    },
    "Flintstone", {
        "FIRST",  "Fred",
        "SPOUSE", "Wilma",
    },
    "Bunker", {
        "FIRST",  "Archie",
        "SPOUSE", "Edith",
    },
);

내부적으로의 키와 값 %personal_info은 모두 스칼라이지만 값은 특수한 종류의 스칼라입니다 {}.. 참조를 통해 "다차원"해시를 시뮬레이션 할 수 있습니다. 예를 들어 다음을 통해 Wilma에 도착할 수 있습니다.

$personal_info{Flintstone}->{SPOUSE}

Perl을 사용하면 아래 첨자 사이에 화살표를 생략 할 수 있으므로 위의 내용은 다음과 같습니다.

$personal_info{Flintstone}{SPOUSE}

That's a lot of typing if you want to know more about Fred, so you might grab a reference as sort of a cursor:

$fred = $personal_info{Flintstone};
print "Fred's wife is $fred->{SPOUSE}\n";

Because $fred in the snippet above is a hashref, the arrow is necessary. If you leave it out but wisely enabled use strict to help you catch these sorts of errors, the compiler will complain:

Global symbol "%fred" requires explicit package name at ...

Perl references are similar to pointers in C and C++, but they can never be null. Pointers in C and C++ require dereferencing and so do references in Perl.

C and C++ function parameters have pass-by-value semantics: they're just copies, so modifications don't get back to the caller. If you want to see the changes, you have to pass a pointer. You can get this effect with references in Perl:

sub add_barney {
    my($personal_info) = @_;

    $personal_info->{Rubble} = {
        FIRST  => "Barney",
        SPOUSE => "Betty",
    };
}

add_barney \%personal_info;

Without the backslash, add_barney would have gotten a copy that's thrown away as soon as the sub returns.

Note also the use of the "fat comma" (=>) above. It autoquotes the string on its left and makes hash initializations less syntactically noisy.


The following demonstrates how you can use a hash and a hash reference:

my %hash = (
    toy    => 'aeroplane',
    colour => 'blue',
);
print "I have an ", $hash{toy}, " which is coloured ", $hash{colour}, "\n";

my $hashref = \%hash;
print "I have an ", $hashref->{toy}, " which is coloured ", $hashref->{colour}, "\n";

Also see perldoc perldsc.


A hash is a basic data type in Perl. It uses keys to access its contents.

A hash ref is an abbreviation to a reference to a hash. References are scalars, that is simple values. It is a scalar value that contains essentially, a pointer to the actual hash itself.

Link: difference between hash and hash ref in perl - Ubuntu Forums

A difference is also in the syntax for deleting. Like C, perl works like this for Hashes:

delete $hash{$key};

and for Hash References

delete $hash_ref->{$key};

The Perl Hash Howto is a great resource to understand Hashes versus Hash with Hash References

There is also another link here that has more information on perl and references.


See perldoc perlreftut which is also accessible on your own computer's command line.

A reference is a scalar value that refers to an entire array or an entire hash (or to just about anything else). Names are one kind of reference that you're already familiar with. Think of the President of the United States: a messy, inconvenient bag of blood and bones. But to talk about him, or to represent him in a computer program, all you need is the easy, convenient scalar string "Barack Obama".

References in Perl are like names for arrays and hashes. They're Perl's private, internal names, so you can be sure they're unambiguous. Unlike "Barack Obama", a reference only refers to one thing, and you always know what it refers to. If you have a reference to an array, you can recover the entire array from it. If you have a reference to a hash, you can recover the entire hash. But the reference is still an easy, compact scalar value.

참고URL : https://stackoverflow.com/questions/1817394/whats-the-difference-between-a-hash-and-hash-reference-in-perl

반응형