Array as value , reference and return perl

Posted: February 6, 2013 in Programming
Tags: , , , , , ,

Being new to perl, array handling through functions seem to be bit difficult. Thought of sharing some possible ways of handling array between the functions.

1. Call by Value

In call by value the changes inside the function wont reflect back.. As you see in the program

size of arr – 1
size of arrnew – 2 ( since the value of arr is passed to this array. The value persist only in function scope)

#!/usr/bin/perl

my @arr = ();
push @arr,"1";
&fun(@arr);
print scalar(@arr);

sub fun()
{
my @arrnew = shift;
push @arrnew,"2";
print scalar(@arrnew);
}

2. Call by reference

In call by reference , the changes made in the function reflects back. Use “\” operator before passing array and whenever we deal with the element of the array we need to add $ to it.. (@$arr).. Here

Size of arrnew is 2

Size of arr is also 2 ( since the changes reflects back)

#!/usr/bin/perl

my @arr = ();
push @arr,"1";
&fun(\@arr);
print scalar(@arr);

sub fun()
{
my $arrnew = shift;
push @$arrnew,"2";
print scalar(@$arrnew);
}

3. Return as array

Once the changes are done, the return value is passed as array.

size of arr – 1
size of arrsub – 2 (modified inside the function)
size of newarr – 2 ( its the return value of arrsub)

#!/usr/bin/perl

my @arr = ();
push @arr,"1";
my @newarr = ();
@newarr = &fun(@arr);
print scalar(@newarr);

sub fun()
{
my @arrsub= shift;
push @arrsub,"2";
print scalar(@arrsub);
return @arrsub;
}
Advertisements

Comments are closed.