A hash/associative array is basically an array where instead of having numerical keys (like an array), the keys can be anything you want. Here is an example that equates an abreviated weekday name with its full name:
Creating a hash
my %weekdays = (
'Sun' => 'Sunday',
'Mon' => 'Monday',
'Tue' => 'Tuesday',
'Wed' => 'Wednesday',
'Thu' => 'Thursday',
'Fri' => 'Friday',
'Sat' => 'Saturday',
);
Retrieving a value from a hash
As you can see, its much the same thing as a normal array, the only difference is that YOU specify the keys that retrieve the data. so to get to the info (value) of the "Wed" key, we do this:
my $day_of_the_week = $weekdays{'Wed'};
# $day_of_the_week variable
# is set to the string (of text): Wednesday
Adding new key/values to a hash
You can just as easily add new items to the array, you do so in the following way:
$weekdays{'some'} = 'someday';
And that will basically add: 'some' => 'someday' to the hash.
Changing the value of an existing hash key
You can change the value of an item in the hash the same way you set it. For example, if we want to change "someday" to "some day" in the example above, then we would do it like this:
$weekdays{'some'} = 'some day';
And the old value of "someday" is overwritten with "some day".
Deleting a key/value from a hash
Deleting a key/value from a hash is likewise simple, we use "delete" to do that. Here is an example that removes the new key we just added above.
delete $weekdays{'some'};
No comments:
Post a Comment