References

References are scalars that refer to other variables

References are like pointers in C in that they refer to other variables.Create a reference with the \ operator.

  1. my $sref = \$scalar;
  2. my $aref = \@array;
  3. my $href = \%hash;
  4. my $cref = \&subroutine;

The thing the reference point to is the "referent".

Dereference a reference with the appropriate sigil, preferably in squiggly braces.

  1. my $other_scalar = ${$sref};
  2. my @other_array = @{$aref};
  3. my %other_hash = %{$href};
  4. &{$cref} # Call the referent.

Arrow pointer is easier way to dereference.

To access array and hashrefs, use the -> operator.

  1. my $stooge = $aref->[1];
  2. my $stooge = $href->{Curly};

ref vs isa

  • A reference belongs to one class
  • You can check this class with ref
  • An object reference can inherit from other classes
  • You can ask an object if it inherited from a class with isa
  • Don't use ref without a good reason
  • isa is part of the UNIVERSAL package, so you can call it on objects
  1. my $mech = WWW::Mechanize->new;
  2. print "ok\n" if $mech->isa('LWP::UserAgent');

References to anonymous subroutines

Subroutines can be assigned to a variable, then called, allowing code references to be passed around and used at will. This can come in handy if, for example, you're writing a subroutine that needs to execute supplied code as part of its work.

  1. my $casefix = sub { return ucfirst lc $_[0] };
  2.  
  3. my $color = $casefix->("rED");
  4. print "Color: $color\n"; # prints Red

TODO

Arrays of arrayrefs, hashes of hashrefs

perldoc perlreftut


Want to contribute?

Submit a PR to github.com/petdance/perl101