11.5. Taking References to Scalars11.5.2. SolutionTo create a reference to a scalar variable, use the backslash operator: $scalar_ref = \$scalar; # get reference to named scalar To create a reference to an anonymous scalar value (a value that isn't in a variable), assign to a dereferenced undefined variable: undef $anon_scalar_ref; $$anon_scalar_ref = 15; This creates a reference to a constant scalar: $anon_scalar_ref = \15; Use ${...} to dereference:
11.5.3. DiscussionIf you want to create many new anonymous scalars, use a subroutine that returns a reference to a lexical variable out of scope, as explained in this chapter's Introduction:
Dereference a scalar reference by prefacing it with $ to get at its contents:
Notice we put braces around $array[0] and $array[1]. If we tried to say $$array[0], the tight binding of dereferencing would turn it into $array->[0]. It would treat $array as an array reference and return the element at index zero. Here are other examples where it is safe to omit the braces:
As mentioned in the Introduction, you may use the ref built-in to inspect a reference for its referent's type. Calling ref on a scalar reference returns the string "SCALAR":
11.5.4. See AlsoChapters 8 and 9 of Programming Perl and perlref(1)
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|