Perl References/Dereferences

An enumerated or comma-separated list always returns the last element in a scalar context.

An array reference is created by either:

  1. * the [ ] operator around a list
  2. * the operator in front of a list variable (@)

A hash reference is created by either:

  1. * the { } operator around a list (of pairs)
  2. * the operator in front of a hash variable (%)

Example Code:

#############################################################

references.pl

#!/usr/bin/perl -w

use strict;

use Data::Dumper;

my @a = qw( hello there you guys ); # a regular array

my %grade = qw( A 4.0 B 3.1 C 2.0 D 1.0 ); # a regular hash

my $aref = @a;

my $bref = [ ‘X’, ‘Y’, ‘Z’ ];

print Dumper $aref, $bref;

print "——————————— 1n";

my $graderef = %grade;

my $ageref = {

John => 50,

Joe => 34,

Ellen => 15,

Marty => 44,

};

print Dumper $graderef, $ageref;

print "——————————— 2n";

# The @mixture array represents an object whose structure is complex

my @mixture = ( $aref, [ 15..18 ], $graderef, $ageref );

# individual components can be accessed in various ways

print Dumper @mixture;

print "——————————— 3n";

print $mixture[0], "n"; # this is the reference $aref

print $mixture[0]->[2], "n"; # explicit deference of $mixture[0] with "->"

print $mixture[1][0], "n"; # implicit deference of $mixture[1]

print "——————————— 4n";

print $mixture[2]->{A}, "n"; # explicit deference of $mixture[2] with "->"

print $mixture[2]{B}, "n"; # implicit deference of $mixture[2] with "->"

print "——————————— 5n";

my @b = @{ $mixture[1] }; # cast reference to back to an array with @{ }

my %h = %{ $mixture[2] }; # cast reference to back to a hash with %{ }

print "$b[2] $h{C}n"; # print to confirm that they are what you think

<

p>#############################################################

Leave a Reply

Your email address will not be published. Required fields are marked *