Pointers and references: Difference between revisions

Content added Content deleted
(→‎[[Perl]]: syntax highlight)
Line 91: Line 91:
'''Interpeter:''' [[Perl]] v5.x
'''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.
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.


<highlightSyntax language=perl>
# start with some var definitions
# start with some var definitions
my $scalar = 'a string';
my @array = ('an', 'array');
my $scalar = 'a string';
my %hash = ( firstkey => 'a', secondkey => 'hash' );
my @array = ('an', 'array');
my %hash = ( firstkey => 'a', secondkey => 'hash' );

# make pointers
# make pointers
my $scalarref = \$scalar;
my $arrayref = \@array;
my $scalarref = \$scalar;
my $hashref = \%hash;
my $arrayref = \@array;
my $hashref = \%hash;
</highlightSyntax>


Using a reference
Using a reference


<highlightSyntax language=perl>
# printing the value
# printing the value
print ${$scalar};
print ${$scalar};
print $arrayref->[1]; # this would print "array"
print $hashref->{'secondkey'}; # this would print "hash"
print $arrayref->[1]; # this would print "array"
print $hashref->{'secondkey'}; # this would print "hash"

# changing the value
# 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
${$scalar} = 'a new string'; # would change $scalar as well
$hashref->{'firstkey'} = 'a good'; # would change the value of the firstkey name value pair in %hash
$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
</highlightSyntax>


You may also create pointers or references without pointing to a previous variable.
You may also create pointers or references without pointing to a previous variable.


<highlightSyntax language=perl>
my $scalarref;
${$scalarref} = 'a scalar';
my $scalarref;
${$scalarref} = 'a scalar';
my $arrayref = ['an', 'array'];
my $hashref = { firstkey => 'a', secondkey => 'hash' }
my $arrayref = ['an', 'array'];
my $hashref = { firstkey => 'a', secondkey => 'hash' }
</highlightSyntax>


==[[Tcl]]==
==[[Tcl]]==