Wednesday, June 4, 2008

Perl: Passing array reference to another function

Share at Facebook

Giving an example of array reference handling in Perl. The example is well commented and if you go through the comments and codes, you'll understand how to handle reference passing. At below example, the main function creates an array with 3 elements and pass the array reference into an intermediate function which will add another three values into the array using the reference. Finally from the main function, again the array passed to another intermediate function to print the 3+3=6 elements using reference.

use strict;


## say this is a main function
sub function_main{
## Initial array with few elements
my @array = qw(1 2 3);
## Pass the array reference to another function for add few elements
## Print the array from another function which takes array reference

## This function takes an array reference
## and add 3 values with the reference
sub function_add_elements{
my $array_reference = shift;
## adding few values
push(@$array_reference, 4);
push(@$array_reference, 5);
push(@$array_reference, 6);

## This function takes an array reference
## and print the elements from the array reference
sub function_print_array{
my $array_reference = shift;
## take each elements from array into $element variable
foreach my $element (@$array_reference){
print "$element\n";

For more Perl related post see here


Anonymous said...

lame. see man perlref

Anonymous said...

thanks. useful to a beginner like me I suppose.