Sunday, 25 November 2018

perl array operations

Declaring an empty array

my @arr = ();

Adding elements in an array 


push( @arr , "hello" ); # directly putting value
my $element = "world";
push( @arr ,  $element ); # putting variable

Printing elements of array 


foreach my $value(@arr) {
     print "$value\n";
}

Passing array as argument in a function
There are two ways to pass a data structure to subroutine/function in perl :
  • Pass by value :

sub printing {
  my @array = @_; # @_ means retrieve all the passed arguments 
  print "priting content of array\n";
  foreach my $value(@array) {
    print "$value\n";
  }
}

printing @arr; # function call

but with this method, you can't change content of array e.g. you may want to add elements in array in subroutine/function.
  • Pass by reference :

sub add {
  my $ref = shift(); # get the first argument
  my $element = shift(); # get the second argument
  push(@$ref,$element);
}
add(\@arr,"Hi"); #\@arr represents reference to arr

you can copy paste the following program in a file (that consist of all of above statements) and try with perl interpreter :

use strict;
use warnings;

sub add {
  my $ref = shift();
  my $element = shift();
  push(@$ref,$element);
}
sub printing {
  my @array = @_;
  print "priting content of array\n";
  foreach my $value(@array) {
    print "$value\n";
  }
}
my @arr = ();
push(@arr,"Hello");
my $w = "world";
push(@arr,$w);
foreach my $value(@arr) {
  print "$value\n";
}
printing @arr;
add(\@arr,"Hii");
printing @arr;


1 comment:

  1. Good post. Can you also write a post mentioning different cases of using refereces in perl?

    ReplyDelete

what is array

Array is one of the simplest and most  sophisticated data structures. In array data is stored at contiguous memory locations. E.g. say you h...