Joe’s Notes on Perl #3 – Referencing, Dereferencing, Extending Arrays and Hashes

So now you’re comfortable with Perl its time to move on to Extending those hashes and arrays.

Referencing – \

An important part of Perl is referencing. A reference is a “pointer” to the data in Perl’s eyes. References must be dereferenced to work.

To reference something in Perl add a backslash before an array or hash.

Dereferencing – {}

Now what good is having this data in a reference? To make it usable again you must dereference it.

Dereferencing depends on the data:

To recap:

Strings

  • Reference: \$string
  • Dereference: ${$reference}

Arrays

  • Reference: \@array
  • Dereference: @{$reference}
  • Access an element: ${$reference}[0]

Hashes

  • Reference: \%hash
  • Dereference: %{$reference}
  • Access a value: ${$reference}{“key”}

Okay, now I expect you’re thoroughly confused. Why use references in the first place?

They can be manipulated very easily.

Array of Arrays

If you have several arrays and you want to smush them into one array then try this:

 

Array of Hashes

Want to store several hashes in an array? Try this.

 

Hash of Arrays

Storing arrays as a value with a key? Try this.

 

Hash of Hashes

Nesting hashes is a-OK.

So as you can see, arrays and hashes are incredibly versatile.

See you later!