Perl Topics





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
Perl Tutorial
Introduction Introduction
Installing Perl Installing Perl
Basics of Perl Basics of Perl
Scalar Variables Scalar Variables
Operators Operators
Control Structures Control Structures
Lists Lists
Array Array
Arrays Manipulation Arrays Manipulation
Arrays Functons Array Functions
Hash Hash
Hash Functions Hash Functions
String Functions String Functions
Regular Expression Regular Expression
Regular Expression Functions Regular Expression Functions
Numerical Functions Numerical Functions
List Functions List Functions
User Defined Function User Defined Function
File Handling File Handling
Forums Ask Your Doubts
Feedback Feedback
 





Add /Replace New values to Hash in Perl


Tutorials Perl

Topic

How to Adding Elements to a Hash structure?
How to replace the same key with different values using Hash?



Explanation

Accessing an element in a hash structure is similar to that from an array, except we replace square brackets with curly ones and instead of an index, the key is used.

     print $name{Tom};

In the above example Tom is equivalent to 'Tom'.To add a new scalar value use the following code.

     $name{Tom} = value;
Example:
    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    %name = ('Tom' => 26, 'Peter' => 51, 'Jones' => 23);
    print "Before Adding:<br>";  
    # In a loop print the hash                      
    while (($key, $value) = each(%name))
    {
      print $key.", ".$value."<br/>";
    }
    # Add a key "Sam" with value "31" is added
    $name{Sam} = 31;    
    # Add a key "Peter" with value "90" is added
    $name{Peter} = 90;  
    print "After Adding:<br>";
    #In a loop print the new hash
    while (($key, $value) = each(%name)) 
    {
      print $key.", ".$value."<br/>";
    }
Result:
    Before Adding values:
    Jones, 23
    Peter, 51
    Tom, 26
    After Adding values:
    Jones, 23
    Peter, 90
    Sam, 31
    Tom, 26

In the above example we are adding the same key ie., "Peter" with a different value ie., "90", so the key is replaced with the new value using a hash structure.






A Note
Simple introduction, basic CGI perl programming codes with examples. Do send your feedback or suggestions on this tutorial. This is a copyright content.

Other Links

web hosting