forked from szabgab/perlmaven.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperl-hashes.tt
180 lines (128 loc) · 5.44 KB
/
perl-hashes.tt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
=title Hashes in Perl
=timestamp 2013-03-19T11:12:06
=indexes hash, keys, value, associative, %, =>, fat arrow, fat comma
=status show
=books beginner_book
=author szabgab
=index 1
=archive 1
=feed 1
=comments 1
=social 1
=abstract start
In this article of the <a href="/perl-tutorial">Perl Tutorial</a>
we are going to learn about <b>hashes</b>, one of the powerful parts of Perl.
Some times called associative arrays, dictionaries, or maps; hashes are one of the data structures available in Perl.
=abstract end
A hash is an un-ordered group of key-value pairs. The keys are unique strings. The values are scalar values.
Each value can be either a number, a string, or a reference. We'll learn about references later.
Hashes, like other Perl variables, are declared using the <hl>my</hl> keyword. The variable name is preceded by the
percentage (<hl>%</hl>) sign.
It's a little mnemonic trick to help you remind about the key-value structure.
Some people think that hashed are like arrays (the old name 'associative array' also indicates this, and in some other
languages, such as PHP, there is no difference between arrays and hashes.), but there are two major differences between arrays
and hashes. Arrays are ordered, and you access an element of an array using its numerical index.
Hashes are un-ordered and you access a value using a key which is a string.
Each hash key is associated with a single <b>value</b> and the keys are all unique inside a single hash structure.
That means no repetitive keys are allowed. (If you really, really want to have more than one values for a key,
you'll will need to wait a bit till we reach the references.)
Let's see some code now:
<h2>Create an empty hash</h2>
<code lang="perl">
my %color_of;
</code>
<h2>Insert a key-value pair into a hash</h2>
In this case 'apple' is the key and 'red' is the associated value.
<code lang="perl">
$color_of{'apple'} = 'red';
</code>
You can also use a variable instead of the key and then you don't need to put the
variable in quotes:
<code lang="perl">
my $fruit = 'apple';
$color_of{$fruit} = 'red';
</code>
Actually, if the key is a simple string, you could leave out the quotes even when you use the string directly:
<code lang="perl">
$color_of{apple} = 'red';
</code>
As you can see above, when accessing a specific key-value pair, we used the <hl>$</hl> sign (and not the % sign)
because we are accessing a single value which is a <b>scalar</b>. The key is placed in curly braces.
<h2>Fetch an element of a hash</h2>
Quite similar to the way we inserted an element, we can also fetch the value of an element.
<code lang="perl">
print $color_of{apple};
</code>
If the key does not exist, the hash will return an <a href="/undef-and-defined-in-perl">undef</a>,
and if <hl>warnings</hl> are enabled, as they should be, then we'll get a
<a href="/use-of-uninitialized-value">warning about uninitialized value</a>.
<code lang="perl">
print $color_of{orange};
</code>
Let's a few more key-value pairs to the hash:
<code lang="perl">
$color_of{orange} = "orange";
$color_of{grape} = "purple";
</code>
<h2>Initialize a hash with values</h2>
We could have instantiated the variable with the key-value pairs simultaneous passing to the hash a list of key-value pairs:
<code lang="perl">
my %color_of = (
"apple" => "red",
"orange" => "orange",
"grape" => "purple",
);
</code>
<hl>=></hl> is called the <b>fat arrow</b> or <b>fat comma</b>, and it is used to indicate pairs of elements.
The first name, fat arrow, will be clear once we see the the other, thinner arrow (->) used in Perl.
The name fat comma comes from the fact that these arrows are basically the same as commas. So we could have written this too:
<code lang="perl">
my %color_of = (
"apple", "red",
"orange", "orange",
"grape", "purple",
);
</code>
Actually, the fat comma allows you to leave out the quotes on the left-hand side makig the code cleaner
and more readable.
<code lang="perl">
my %color_of = (
apple => "red",
orange => "orange",
grape => "purple",
);
</code>
<h2>Assignment to a hash element</h2>
Let's see what happens when we assign another value to an existing key:
<code lang="perl">
$color_of{apple} = "green";
print $color_of{apple}; # green
</code>
The assignment changed the value associated with the <b>apple</b> key. Remember, keys are unique and each key has a
single value.
<h2>Iterating over hashes</h2>
In order to access a value in a hash you need to know the key.
When the keys of a hash are not pre-defined values you can use the <hl>keys</hl> function
to get the list of keys. Then you can iterate over those keys:
<code lang="perl">
my @fruits = keys %color_of;
for my $fruit (@fruits) {
print "The color of '$fruit' is $color_of{$fruit}\n";
}
</code>
You don't even need to use the temporary variable <hl>@fruits</hl>, you can iterate
over directly the return values of the <hl>keys</hl> function:
<code lang="perl">
for my $fruit (keys %color_of) {
print "The color of '$fruit' is $color_of{$fruit}\n";
}
</code>
<h2>The size of a hash</h2>
When we say the size of a hash, usually we mean the number of key-value pairs.
You can get it by placing the <hl>keys</hl> function in scalar context.
<code lang="perl">
print scalar keys %hash;
</code>
<h2>Thanks</h2>
The first edition of this article was written by <a href="http://www.leprevost.com.br/">Felipe da Veiga Leprevost</a> who also makes the
<a href="http://br.perl5maven.com/">Portuguese translation</a> of the Perl Maven articles.