Thursday, October 20, 2022

Find length of an array in perl

 

@fruits = ("Orange", "Grapefruit", "Lemon");#initializing associative array
print "Length of fruits array is " . scalar(@fruits);

Shift and Unshift in perl

 

@alphabets = (a .. f);

print "Original: @alphabets \n";
shift (@alphabets);   # removing first element of the array

print "Removing first element from an array: @alphabets\n";

unshift (@alphabets, 'a');   # adding last element of the array

print "Adding first element to an array: @alphabets";

push and pop in perl

 @alphabets = (A .. F);

print "Original: @alphabets \n";
push (@alphabets, 'G');   # add G to the last index array

print "Pushing G in the array: @alphabets\n";

pop (@alphabets);   # removing last element of array

print "Removing last element from array: @alphabets\n";
pop (@alphabets);   # removing last element of array

print "Removing last element from array: @alphabets\n\n";

Declare and print an array in perl

 

@fruits = ('Grapes', 'Apple', 'Banana' );

print "@fruits";

Substring in perl

 

$foo = "Hello world";

@arr = split("",$foo);
print $arr[6]; # returns w
print "\n";

print substr($foo, 6, 5); # returns 'world'
 

Finding position of a substring

In Perl, we can use the index method to get the first position/occurrence of a substring

 

 in another string. If the substring does not exist, the index returns -1.

 

 

$str = "The occurence of hay is hay at position:";

print $str . index($str, "hay")."\n";