Home >> perldatatypes >>Perl ReferencesI'm happiest writing Perl code that does not use references because they always give me a mild headache. Here's the short version of how they work. The backslash operator () computes a reference to something. The reference is a scalar that points to the original thing. The '$' dereferences to access the original thing. Suppose there is a string...$str = "hello"; ## original string And there is a reference that points to that string... $ref = $str; ## compute $ref that points to $str The expression to access $str is $$ref. Essentially, the alphabetic part of the variable, 'str', is replaced with the dereference expression '$ref'... print "$$refn"; ## prints "hello" -- identical to "$strn"; Here's an example of the same principle with a reference to an array... @a = (1, 2, 3); ## original array $aRef = @a; ## reference to the array print "a: @an"; ## prints "a: 1 2 3" print "a: @$aRefn"; ## exactly the same Curly braces { } can be added in code and in strings to help clarify the stack of @, $, ... print "a: @{$aRef}n"; ## use { } for clarity Here's how you put references to arrays in another array to make it look two dimensional... @a = (1, 2, 3); @b = (4, 5, 6); @root = (@a, @b); print "a: @an"; ## a: (1 2 3) print "a: @{$root[0]}n"; ## a: (1 2 3) print "b: @{$root[1]}n"; ## b: (4 5 6) scalar(@root) ## root len == 2 scalar(@{$root[0]}) ## a len: == 3 For arrays of arrays, the [ ] operations can stack together so the syntax is more C like... $root[1][0] ## this is 4 Perl functions
|
Perl @ARGV %ENV Perl Arrays Perl Data Types Perl Hash Perl list Perl Scalar data types Perl Special Variables
|