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 |
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 $scalar = 'a string'; |
|||
my @array = ('an', 'array'); |
|||
my %hash = ( firstkey => 'a', secondkey => 'hash' ); |
|||
# make pointers |
|||
⚫ | |||
my $scalarref = \$scalar; |
|||
my $arrayref = \@array; |
|||
my $hashref = \%hash; |
|||
</highlightSyntax> |
|||
Using a reference |
Using a reference |
||
<highlightSyntax language=perl> |
|||
# printing the value |
|||
print ${$scalar}; |
|||
⚫ | |||
print $arrayref->[1]; # this would print "array" |
|||
⚫ | |||
# changing the value |
|||
${$scalar} = 'a new string'; # would change $scalar as well |
|||
${$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 |
|||
</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; |
|||
my $scalarref; |
|||
⚫ | |||
my $arrayref = ['an', 'array']; |
|||
my $arrayref = ['an', 'array']; |
|||
my $hashref = { firstkey => 'a', secondkey => 'hash' } |
|||
</highlightSyntax> |
|||
==[[Tcl]]== |
==[[Tcl]]== |