Wednesday, June 4, 2008

Perl: Returning array reference from function.


Share at Facebook

My last post http://icfun.blogspot.com/2008/06/perl-passing-array-reference-to-another.html I have given an example to handle the array reference handling. Now I'm giving an example of how to return an array reference and play with the referenced pointer. The example is almost looks similar of last one. In this case I just added the returning array reference.

use strict;

main_process();

## say just a main function
sub main_process{
## grab the returned array pointer
my $array_ref = get_array_ref();
## delete using array pointer
$array_ref = delete_elements_from_ref($array_ref);
## print using array pointer
print_array_ref($array_ref);
}

## This function makes an array
## and return the array reference to caller function.
sub get_array_ref{
my @array = (1,2,3,4,5);
## return array reference.
return \@array;
}

## This function takes an array reference
## And delete last 2 elements from the array using reference
sub delete_elements_from_ref{
my $ref = shift;
## drop last 2 elements
pop(@$ref);
pop(@$ref);
## return array reference
return $ref;
}

## This function takes an array reference
## And print the elements from the array
sub print_array_ref{
my $ref = shift;
foreach my $item(@$ref){
print $item,"\n";
}
}

For more Perl post see here http://icfun.blogspot.com/search/label/perl Or you can search my blog for other programming languages.




1 comment:

Anonymous said...

Thanks alot for this. This is the first time I'm using Perl so alot of things are a little bit confusing for me. Now I now how to access an array returned from a function. Exactly what I needed.