Pointers and references: Difference between revisions

No edit summary
Line 91:
'''Interpeter:''' [[Perl]] v5.x
 
References are essentially how perl handles pointers. Any scalar value, element in an array, key of a hash, or value of a hash may contain a reference to any other variable structurer.
 
# start with some var definitions
my $scalar = 'a string';
my @array = ('an', 'array');
my %hash = ( firstkey => 'a', secondkey => 'hash' );
# make pointers
my $scalarref = \$scalar;
my $arrayref = \@array;
my $hashref = \%hash;
 
Using a reference
 
# printing the value
print ${$scalar};
print $arrayref->[1]; # this would print "array"
print $hashref->{'secondkey'}; # this would print "hash"
# changing the value
${$scalar} = 'a new string'; # would change $scalar as well
$arrayref->[0] = 'an altered'; # would change the first value of @array as well
$hashref->{'firstkey'} = 'a good'; # would change the value of the firstkey name value pair in %hash
 
You may also create pointers or references without pointing to a previous variable.
 
my $scalarref;
${$scalarref} = 'a scalar';
my $arrayref = ['an', 'array'];
my $hashref = { firstkey => 'a', secondkey => 'hash' }
 
==[[Tcl]]==
Anonymous user