Pointers and references: Difference between revisions

→‎[[Perl]]: syntax highlight
(→‎[[Perl]]: syntax highlight)
Line 91:
'''Interpeter:''' [[Perl]] v5.x
 
References are essentially how perlPerl 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$scalar = ('an',a string'array');
my %hash@array = ( firstkey => 'aan', secondkey => 'hasharray' );
my %hash = ( firstkey => 'a', secondkey => 'hash' );
 
# make pointers
my $scalarref = \$scalar;
my $arrayrefscalarref = \@array$scalar;
my $hashrefarrayref = \%hash@array;
my $hashref = \%hash;
</highlightSyntax>
 
Using a reference
 
<highlightSyntax language=perl>
# printing the value
print ${$scalar};
print $arrayref->[1]; # this would print "array"
print $hashrefarrayref->{'secondkey'}[1]; # this would print "hasharray"
print $arrayrefhashref->[1]{'secondkey'}; # this would print "arrayhash"
 
# changing the value
${$scalar} = 'a new string'; # would change $scalar as well
$arrayref->[0]{$scalar} = 'ana alterednew string'; # would change the first value of# @arraywould change $scalar as well
$hashrefarrayref->{'firstkey'}[0] = 'aan goodaltered'; # would change the first value of the firstkey name value pair@array inas %hashwell
$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.
 
<highlightSyntax language=perl>
my $scalarref;
${my $scalarref} = 'a scalar';
my ${$scalarref} = \$'a scalar';
my $arrayref = ['an', 'array'];
my $hashrefarrayref = { firstkey => ['aan', secondkey => 'hasharray' }];
my $hashref = { firstkey => 'a', secondkey => 'hash' }
</highlightSyntax>
 
==[[Tcl]]==
14

edits