Wednesday, June 4, 2008

Perl: Returning array reference from function.

My last post 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;


## 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

## 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
## 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 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.

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...