Perl survival guide – references

When starting up perl, the one thing that gave me headaches was all the different signs like “@$->%{}[]” and the different use of it. It took me quite a while before I started to get a feeling of the programming language inspired by Donald Duck’s cursing.

The motto of perl is “There’s more than one way to do it”. My focus will be on the way I prefer.

References, dereferences and the likes
Declares an array: my @array = (1, 2, 3);
Declares a reference to an array: my $array = [1, 2, 3];

Declares a hash: my %hash = (‘key1’ => ‘value’, ‘key2’ => ‘another value’);
Declares a reference to a hash: $hash = {‘key1’ => ‘value’, ‘key2’ => ‘another value’};

To know what data type you’re dealing with use Data::Dumper. If you see paranthesis you’re dealing with the object itself like an array or an hash. If you see “[]” or “{}” it’s a referenced object. If you want to fetch the values of referenced objects, you have to dereference it.

my $value = $array[0]; #Fetches a value from the array
my $refvalue = $array->[0] #Fetches a value from the referenced array.

my $hash_value = $hash{‘id’}; # Fetches the id from the hash
my $hashref = $hash->{‘id’}; # Fetches the value from the hash reference

Putting it all together
use Data::Dumper;

my @categories = (); # An array

# Adds a hash reference to the array
push( @categories, {‘id’ => 1, ‘title’ => ‘perl’ } );
push( @categories, {‘id’ => 2, ‘title’ => ‘python’ } );

# Adds an array reference to the hash reference above
$categories[0]{‘developers’} = [];

# Add values to the developers array reference above
# @{} is used to announce that it’s an array reference
# In the case of a foreach it fetches each entry in the array reference
push( @{$categories[0]{‘developers’}}, ‘Helene’);
push( @{$categories[0]{‘developers’}}, ‘Martin’);

print Dumper @categories;

The result of the print line:
$VAR1 = {
‘developers’ => [
‘title’ => ‘perl’,
‘id’ => 1
$VAR2 = {
‘title’ => ‘python’,
‘id’ => 2

About Haridasi

integrity - the state of being whole, entire, or undiminished.
This entry was posted in Technology. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *