Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 69 lines (42 sloc) 1.715 kb
d5f3b1b @petdance Importing from Andy original repo
authored
1 =head1 References
2
3 =head2 References are scalars that refer to other variables
4
5 References are like pointers in C in that they refer to other
6 variables. Create a reference with the C<\> operator.
7
8 my $sref = \$scalar;
9 my $aref = \@array;
10 my $href = \%hash;
11 my $cref = \&subroutine;
12
13 The thing the reference point to is the "referent".
14
15 Dereference a reference with the appropriate sigil, preferably in
16 squiggly braces.
17
18 my $other_scalar = ${$sref};
19 my @other_array = @{$aref};
20 my %other_hash = %{$href};
21 &{$cref} # Call the referent.
22
23 =head2 Arrow pointer is easier way to dereference.
24
25 To access array and hashrefs, use the C<< -> >> operator.
26
27 my $stooge = $aref->[1];
28 my $stooge = $href->{Curly};
29
30 =head2 ref vs isa
31
32 =over
33
34 =item * A reference belongs to one class
35
36 =item * You can check this class with C<ref>
37
38 =item * An object reference can inherit from other classes
39
40 =item * You can ask an object if it inherited from a class with C<isa>
41
42 =item * Don't use C<ref> without a good reason
43
44 =item * C<isa> is part of the UNIVERSAL package, so you can call it on objects
45
46 my $mech = WWW::Mechanize->new;
47 print "ok\n" if $mech->isa('LWP::UserAgent');
48
49 =back
50
51 =head2 References to anonymous subroutines
52
53 Subroutines can be assigned to a variable, then called,
54 allowing code references to be passed around and used at will.
55 This can come in handy if, for example, you're writing a
56 subroutine that needs to execute supplied code as part of
57 its work.
58
59 my $casefix = sub { return ucfirst lc $_[0] };
60
61 my $color = $casefix->("rED");
62 print "Color: $color\n"; # prints Red
63
64 =head2 TODO
65
66 Arrays of arrayrefs, hashes of hashrefs
67
68 C<< perldoc L<perlreftut> >>
Something went wrong with that request. Please try again.