Home » Perl Basics » 03 - Variables
The third element is a key and the forth a value.
The fifth element is a key and the sixth a value etc…
The key is what you will define the value is the actual variable.
NOTE : Perl is case sensitive and print “$Contact_form{name}” IS NOT EQUAL TO print “$Contact_form{Name}”;.
3
Hashes
Hash is defined with a key/value relationship
The last variable type in Perl is the HASH variable. HASH is a type of variable that is defined with a key/value relationship. The specific sign for a HASH is the % sign.
To create a HASH variable
%Contact_form = (“name” , “marc” , “last name” , “ doe” , “address” , “ 25th masson street” , “phone” , “ 555 2121”);The first element is a key and the second a value.
The third element is a key and the forth a value.
The fifth element is a key and the sixth a value etc…
The key is what you will define the value is the actual variable.
print “$Contact_form{name}”;
This is how you call a specific value. NOTE : Perl is case sensitive and print “$Contact_form{name}” IS NOT EQUAL TO print “$Contact_form{Name}”;.
That kind of variable advantage in treating forms and such is obvious.
If the form to be treate is of good size, the variable creation can be harder to read. To remedy that you can get the variable declaration on more than one line.
%Contact_form = ( Name => “marc”, Last name => “doe”, Address => “25th masson street”, Phone => “555 2121”, );This method is much more readable for you and anyone who might read your code.
NOTE : the key does not need to be in quotes but the value does.
You may want to extract the values or the keys from the HASH variable and assign them to an array. To do so declare a new array variable
@name-of-your-array = keys %name-of-your-HASH; This will extract all the keys of your HASH and populate the array.
@name-of-your-array = values %name-of-your-HASH; This will extract all the values of your HASH and populate the array.