![]() |
VOOZH | about |
Hash in LIST Context
The assignment of a hash to a list type in Perl is accomplished by making a list with the keys and values as its elements. When a hash is in LIST context, Perl converts a hash into a list of alternating values. Each key-value pair in the original hash will become two values in the newly created list.Syntax : my @list = %hash;An interesting fact about this resulting list is that for every pair the key will come first and the value will come after. Examples
$VAR1 = [ 'Yellow', 'Look and move', 'Green', 'Go', 'Speed', '60.7', 'MyVehicle', 'Car', 'Red', 'Stop', 'Model', 1234 ];
$VAR1 = {
'Yellow' => 'Look and move',
'Red' => 'Stop',
'MyVehicle' => 'Car',
'Green' => 'Go',
'Speed' => '60.7',
'Model' => 1234
};
@hundred = (0..100);Above example if put into a print statement will result in printing a range of numbers from 0 to 100.
@keys = keys %hash; if (@keys) { ....Code.... }
Hash in SCALAR context
The assignment of a hash to a scalar type in Perl will actually give some internal number representing the internal layout of the hash. The return type is string that describes the current storage statistics for the hash. This is reported as “used/total” buckets. The buckets are the storage containers for your hash information. The obtained string looks like a fraction which can be evaluated as:The denominator of the fraction is the total number of buckets. The numerator of the fraction is the number of buckets which has one or more elements.
Syntax : my $list = %hash;Examples
5/8
my $list = %hash; if ($list) { ....Code.... }The if condition will be executed if the hash is non-empty.
@keys = keys %hash; $size = @keys;Here, $size will return the size of the hash.