Perl - Hash


How can we create a hash?

%hashName = qw(fred camel barney llama betty alpaca wilma);
%hashName = qw( key_value_pairs );

How can we access a hash?


while (($first, $last) = each(%hashName)) { ... }

How can we get an array of hash keys?


How can we get an array of hash values?


How can we assign a value to a hash?

$hashName{"key"} = value;

How can we assign multiple values to a hash?

@score{"fred", "barney", "dino"} = (205, 195, 30);

How can we delete an element from a hash?

delete $hashName{"key"};

How can we merge hashes?

@league{keys %score} = values %score; // merge %score into %league
%league=(%league, %score); // same as above but much slower

How can we determine if a hash contains a particular key?

exist $hashName{'key'} // return true if the specified key exists regardless of value

What is a hash slice?

@sound{"cat", "goldfish", "dog", "dolphin"};

I think a hash slice is an array.

How can we access a hash reference?

$hashref->{'key'} = value;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License