Perl is a powerful script language which is much faster than simple shell script and there are lots of libraries that support virtually every tasks out there. But it is little difficult to learn at first.

One of the weak area of perl is that it doesn’t support multi dimensional array naturally. In order to implement multi dimensional array, you will need to use pointer references. (There may be other ways)

You can referece variable and array by adding "\" backslash in front of the variable.

For example

#create array
@a = (1,2,3,4,5,6);
 
#create reference to array a
$aref=\@a;

In order to access the variable,you just add the proper symbol in front of the var name.
You will need to use the referenced variable name with the ‘$’ sign intact.

  • if you are accessing it as a array , @$ref would refer to the whole array
  • if you are accessing the element of the array , $$ref[0] would refer the first element.
#To access the first element of the referenced array
print "first element: " . $$arref[1] . "\n";  # this will print '2'


To find Referenced Array’s length, you use the same convention. Just like the regular array, you put $# in front of the referenced array’s name. Note the curly bracket will help you to read source code more clearly.

print "array length is ". $#{$arref}  . " or " . $#$arref  . "\n"; 
#array length is 5 or 5

$# convention returns the length – 1 . So in fact the actual length is 6.

Here is the complete example.

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/perl -w
use strict;
 
my @a = qw(one two three four five six);
my $aref = \@a;
 
 
print "-- Actual Array --\n";
print "Number of elements in the array: $#a\n"; 
 
print "-- Reference --\n";
print "Number of elements in the array (ref): ". $#{$aref} . "\n";
print "Number of elements in the array (ref): " . @$aref . "\n";

Output

$> perl test.pl
-- Actual Array --
Number of elements in the array: 5
-- Reference --
Number of elements in the array (ref): 5
Number of elements in the array (ref): 6
Share and Enjoy:
  • DZone
  • Twitter
  • Technorati
  • Reddit
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Diigo


Leave a Reply