A little off topic, but references are also the only way
you can create a perl object or multi dimensional data structures.
Perl doesnt really have 2D arrays, but we can still make
them by create an array of array references.
And with
objects the object is really a reference to a data structure
of some kind (usually a hash), so when you pass an object
to a function you are really only passing a reference to a memory
address. The actual data of the object stays in a fixed
memory location and is not copied anywhere.
BBQ asked for some code to help explain so I hope this helps:
#!/usr/bin/perl
use strict;
# create some table rows
my @a = qw(a b c);
my @b = qw(c d e);
my @c = qw(f g h);
# create the 2D structure.
my @table = (\@a, \@b, \@c);
# @table is really a 1D structure, of references
# but conceptually you can treat it as a 2D structure
# (see the print_cube function)
# this prints just the references
print join(" ", @table), "\n\n";
# this function prints out the table
print_cube(@table);
# but since @table holds only references, you can change
# the data being referenced and @table will in turn change
# because they are really pointing the same thing
@a = qw(x y z);
print_cube(@table);
# that is why multi dimensional structures are usually create
# with anonymous structures:
$table[0] = [1, 2, 3];
$table[1] = [4, 5, 6];
$table[2] = [7, 8, 9];
# that way to access the first row you have to go through
# the table structure because the first row has not other
# name than $table[0] (unlike @a above)
print_cube(@table);
sub print_cube
{
my @cube = @_;
foreach my $i (0..2)
{
foreach my $j (0..2)
{
print $cube[$i][$j], " ";
}
print "\n";
}
print "\n";
}
And the code results:
ARRAY(0x80e4ac0) ARRAY(0x80e4afc) ARRAY(0x80e8bc0)
a b c
c d e
f g h
x y z
c d e
f g h
1 2 3
4 5 6
7 8 9
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.