·  PERL – Syntax – Collections – Hash

 

- Info:

  - Hash is structure that holds variables itendified by their unique key.

  - Hash name must start with '%' whose circles resemble key-value pairs that are stored in a Hash.

  - If hash is created without name, using only reference, then it is called Anonymous Hash.

 

- Create:

  %hash = (John=>25,Jill=>33);              

  %hash = ("Key1", "Value1", Key2, Value2);   #Using      ','          to connect keys with values.

  %hash = ("Key1"=>"Value1", Key2=>Value2);   #Using      '=>'         to connect keys with values.

  %hash = ("Key1"=>"Value1", Key2, Value2);   #Using both ',' and '=>' to connect keys with values.

  %hash = (                                   #Key-value pairs can be defined in separate lines.

    John => 25,

    Jill => 33,

  );

 

- Add/Edit Element(s):

  $hash{Bob}  = 55;                 #Add new key-value pair Bob-55.

  $hash{John} = 20;                 #Change value of an existing key-value pair.

 

- Remove Element(s):

  delete($hash{John});              #Remove key-value pair where key is John.

 

- Get Element(s):

  $age    = $hash{John};            #25.                Get value of element with key "John".

  @array  = %hash;                  #[John,25,Jill,22]. Store key-value pairs into array.

  @keys   = keys  (%hash);          #[Jill,John].       Store keys            into array.

  @values = values(%hash);          #[33,25].           Store values          into array.

 

- Cycle through elements:

  %hash = (John=>25,Jill=>33);

  while ( ($key,$value) = each(%hash) ) { #Function each returns next key-value pair.

    print("$key=$value\n");

  }

 

- Display:

  print %hash;                      #Jill33John25. Display all key-value pairs.