Jump to content

Pointers and references: Difference between revisions

→‎[[Perl]]: -> remove syntax hilighting
(→‎[[Perl]]: -> remove syntax hilighting)
Line 93:
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
my $scalar = 'a string';
my @array = ('an', 'array');
my %hash = ( firstkey => 'a', secondkey => 'hash' );
 
# start with some var definitions
# make pointers
my $scalarrefscalar = \$scalar'a string';
my $arrayref@array = \@('an', 'array');
my %hash = ( firstkey => 'a', secondkey => 'hash' );
my $hashref = \%hash;
 
</highlightSyntax>
# make pointers
my $scalarref = \$scalar;
my $arrayref = \@array;
my $hashref = \%hash;
 
 
Using a reference
 
<highlightSyntax language=perl>
# printing the value
print ${$scalar};
print $arrayref->[1]; # this would print "array"
print $hashref->{'secondkey'}; # this would print "hash"
 
# changingprinting the value
print ${$scalar};
${$scalar} = 'a new string'; # would change $scalar as well
print $arrayref->[01]; = 'an altered'; # would change# thethis firstwould valueprint of @"array as well"
print $hashref->{'firstkeysecondkey'} = 'a good'; # this would change the value of the firstkey name value pair inprint %"hash"
 
</highlightSyntax>
# printingchanging 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.
 
 
<highlightSyntax language=perl>
my $scalarref;
${$scalarref} = 'a scalar';
my $arrayref = ['an', 'array'];
my $hashref = { firstkey => 'a', secondkey => 'hash' }
</highlightSyntax>
 
==[[Tcl]]==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.