Initializing a hash in Perl
There are two ways to initialize a hash; one is very similar to that of an array:
%hash = (
"key1", "value1",
"key2", "value2",
"key3", "value3"
);
Here the hash is initialized from a normal list, taking every two scalars as the key/value pair.
The other way is specific to the hash structure:
%hash = (
key1 => "value1",
key2 => "value2",
key3 => "value3",
);
The =>
operator is similar to the comma, but it implicitly quotes the value to the left of it, treating it as a literal string.
This is a more convenient method of initializing a hash, and we will use it almost exclusively in this course.
Here's an example, using our Best Picture data from the array examples:
The chmod settings for a Perl file on the server must be set to 755.
%bestpix = (
1990 => "Dances with Wolves",
1991 => "The Silence of the Lambs",
1992 => "Unforgiven",
1993 => "Schindler's List",
1994 => "Forrest Gump",
1995 => "Braveheart",
1996 => "The English Patient",
1997 => "Titanic",
);
This creates a hash with the year of the award for the key and the title of the film for the value.