← Back to Perl Course | Chapter 2: Variables | Lesson 5 of 7

Hashes का परिचय

एक hash keys और values के pairs store करता है ताकि आप नाम से चीज़ें ढूंढ सकें।

In this page:

  1. Hashes

Hashes

Hash names % से शुरू होते हैं और आप $hash{key} से एक value fetch करते हैं। Keys strings हैं और keys का order defined नहीं है, इसलिए जब आपको predictable output चाहिए keys sort करें। एक key test करने के लिए exists इस्तेमाल करें, एक remove करने के लिए delete, और contents के आर-पार चलने के लिए keys, values, और each।

Note: fat comma => इसके left पर word quote करता है, इसलिए आप name के चारों ओर quotes के बिना name => "Ada" लिख सकते हैं।

उदाहरण: Hashes

perl
use strict;
use warnings;

my %ages = (
    Alice => 30,
    Bob   => 25,
);
$ages{Carol} = 41;
print "Bob is $ages{Bob}\n";
print "Has Dave? ", (exists $ages{Dave} ? "yes" : "no"), "\n";
delete $ages{Bob};
for my $name (sort keys %ages) {
    print "$name => $ages{$name}\n";
}
print "count: ", scalar(keys %ages), "\n";
my %inverse = reverse %ages;
print "who is 30? $inverse{30}\n";

# Output:
# Bob is 25
# Has Dave? no
# Alice => 30
# Carol => 41
# count: 2
# who is 30? Alice
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक particular key order पर depend करना
  2. key की बजाय value पर exists इस्तेमाल करना
  3. $hash{key} लिखना जब hash %hash कहलाता है लेकिन element पर @ या % इस्तेमाल करना
चैप्टर सारांश
  • Hashes % से शुरू होते हैं
  • Values $hash{key} इस्तेमाल करते हैं
  • Key order guaranteed नहीं है इसलिए keys sort करें
  • exists और delete keys पर काम करते हैं
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.