Creating arrays and hashes in perl
Creating arrays and hashes in perl
I’m sure for those users looking for dynamically storing their information they will most likely rely at some point on arrays. Here are some quick snippets on how to create arrays and associative arrays in perl (hashes).
Creating an array in perl
Arrays are preceded by the symbol “@”, these are standard arrays used for simple loops of data. For example:
1 2 3 |
my @local_array = ("Andrew", "Anthony", "Andy"); print $local_array[0]; // This will print "Andrew" |
This is a really simple usage of an array.
Creating an associative array in perl (hashes)
These are actually called hashes (“%”) in perldocs, but for me its easier to call them associative arrays because are really similar to this. The usage is slightly different than normal arrays in perl, see below:
1 2 3 4 5 |
my %local_hash; $local_hash{"some_id"} = "some value"; $local_hash{"another_id"} = "another value"; print $local_hash{"another_id"}; // This will print "another value" |
It is clearly similar to associative arrays, correct?
Creative hashes of hashes in perl
Now here’s the really big stuff, when going even more advance, you would use multi level arrays, this is usually used with hashes, see below:
1 2 3 4 5 6 7 8 |
our (%first_hash, %second_hash, @some_array); $first_hash{"some_id"} = "some value"; $some_array = ("Andy", "Andrew"); %second_hash{"other_id"} = %first_hash; // Or using arrays %second_hash{"another_id"} = @some_array; |
The same for arrays of arrays, its really that simple. You can then create a multi level array or hashes or array of array or hashes of hashes, from there you really have a lot of freedom.