If you understand arrays, hashes aren't really that different. Suppose you have an array called @race_results, containing an ordered list of the names of people who finished a race. Ignoring the 0th element to make things convenient, you could associate the position in the array with the name as follows:
1 -> Bob
2 -> Joe
3 -> Sunny
4 -> Hannah
It follows, if you want to find out who came in first, you would use the code $race_results[1].
If you follow that, then hashes aren't too difficult. The only effective difference is that they're not accessed by number. There's no particular order. Instead, it's like a dictionary, where you look up a definition by the word. You might create a hash called %race_results like this:
my %race_results = (
first => 'Bob'
second => 'Joe',
third => 'Sunny',
fourth => 'Hannah',
);
To find out who came in first, say $race_results{first};.
Think of it like an array, where you use strings instead of numbers, and you'll have it. (It's not completely accurate under the hood, but that's how I first approached it, and it's a decent mental model.)
Use them whenever you have one string to associate with another, and you want to be able to look something up as you would in an encyclopedia or a dictionary. If you can look at the world in terms of indexes, you'll have your keys. |