Perl reference

If you ever used c++, it will be easier to get the concept of reference in Perl.

Here is an example of reference to hash.
my %hash = (
    date => '08-10-2014',
);

my $ref = \%hash;

#note: In c++ we use '->' to access members of an object reference
print $ref->{date}."\n";

#note: In c++ we use '.' to access members of an object. 
print $hash{date}."\n";

Here are more examples
#reference to anonymous hash
my $ref1 = {
    date => '08-10-2014',
};

#reference to anonymous array
my $ref2 = [1,2,3,4,5];

#please note the way to access the index.
print $ref2->[4]."\n"; #output is 5.

Dereference:
#hash
%{$ref1} 

#array
@{$ref2}

No comments:

Post a Comment