Open In App

Perl | Hash in Scalar and List Context

Last Updated : 18 Jun, 2019
Improve
Improve
Like Article
Like
Save
Share
Report
    Prerequisite: Perl Hash

Hash in Perl is a set of key/value pairs. Perl provides us the flexibility to assign the hash to a List type and a Scalar type, known as LIST Context and SCALAR Context respectively.

    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




    # !/usr/bin/perl
    # Perl program to demonstrate
    # List Context of hash
      
    use strict; 
    use warnings;
    use 5.010;
    use Data::Dumper qw(Dumper);
      
    # Creating a Hash
    my %hash = ('MyVehicle' => 'Car'
            'Model' => 1234, 
            'Speed' => 60.7,     
            'Red' => 'Stop',         
            'Yellow' => 'Look and move'
            'Green' => 'Go'
           ); 
      
    # Assign hash to a list context
    my @list = %hash;
      
    # Print the List
    say Dumper \@list;

    
    

    Output:

    $VAR1 = [
              'Yellow',
              'Look and move',
              'Green',
              'Go',
              'Speed',
              '60.7',
              'MyVehicle',
              'Car',
              'Red',
              'Stop',
              'Model',
              1234
            ];
    

    Here, we can see that each value of the hash is placed in the list after its corresponding key. But the order in which these pairs will be placed in the list is not defined.

    Data::Dumper is used to serialize the hash and the list. This module provides methods for resolving a data structure (including objects) into a string format that can be used both to “dump” the data for printing and to make an evaluation so that a dumped structure can be reconstituted with eval into a valid internal structure.

    The primary function Dumper accepts a list of scalar references to data structures or objects. The return value is a string representation of the structure, produced in normal string syntax format.

    Example




    # !/usr/bin/perl
    # Perl program to demonstrate
    # Use of Data::Dumper
      
    use Data::Dumper;
      
    my $ref = { 'MyVehicle' => 'Car'
            'Model' => 1234, 
            'Speed' => 60.7,     
            'Red' => 'Stop',         
            'Yellow' => 'Look and move'
            'Green' => 'Go'
          }; 
      
    print Dumper($ref);

    
    

    Output:

    $VAR1 = {
              'Yellow' => 'Look and move',
              'Red' => 'Stop',
              'MyVehicle' => 'Car',
              'Green' => 'Go',
              'Speed' => '60.7',
              'Model' => 1234
            };
    

    Uses of LIST Context in hash:

  1. In the List context in Perl, the operator can be used to obtain multiple values between the supplied range.
    Example:

    @hundred = (0..100);
    

    Above example if put into a print statement will result in printing a range of numbers from 0 to 100.

  2. The sorting of a hash by its keys or values can be easily accomplished by using List Context. After converting the hash into a list of its keys or values, sort that list and then store the corresponding keys or values in the sorted order.
  3. We can also use the List Context of hash where we want to execute a piece of code only when the hash is non-empty, that is the size of hash is not 0.
    Syntax

    @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




    # !/usr/bin/perl
    # Perl program to demonstrate
    # Scalar Context of hash
      
    # Creating a Hash
    my %hash = (
            'MyVehicle' => 'Car'
            'Model' => 1234, 
            'Speed' => 60.7,     
            'Red' => 'Stop',         
            'Yellow' => 'Look and move'
            'Green' => 'Go'
            ); 
      
    # Assign hash to a Scalar Context
    my $list = %hash;
      
    # Print the List
    print $list;

    
    

    Output:

    5/8
    

    In the above output, there are in total 6 buckets(all key/value pairs) in the hash and therefore the total allocated
    buckets will be the lowest power of 2 > total keys, for full accommodation of all the buckets, therefore denominator is 8.
    While the numerator totally depends on the internal algorithm as it keeps on changing its value depending upon the hash storage properties.
    However, once the hash has allocated its buckets, they will remain allocated even if we shrink the hash.

    NOTE: For hashes with the same number of elements, the higher the number, the better. The one that returns 6/8 has fewer collisions than the one that returns 4/8.

    Uses of SCALAR Context in hash:

  1. The Scalar context of a hash helps to determine whether the hash is empty or not. It returns 0 if the hash
    is empty.

    my $list = %hash;
    if ($list)
    {
    ….Code….
    }

    The if condition will be executed if the hash is non-empty.

  2. It helps in finding out whether Perl’s internal hashing algorithm is performing poorly on our data set.

    For example,
    We place 10 things in a hash, but evaluating %HASH in scalar context reveals “1/16”, which means only one out of sixteen buckets has been touched and presumably contains all 10 of your items. This isn’t supposed to happen.

  3. Also we can get the size – that is, the number of elements from a hash by using the scalar context on
    either keys or values.

    Syntax

    @keys = keys %hash;
    $size = @keys;

    Here, $size will return the size of the hash.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads