Add/Remove Elements in an Array


Add/Remove Elements Array – AyeSir.org


Adding and Removing Elements in an Array:

Elements can be added or removed from an Array in Perl using functions push (), pop(), unshift (), shift()

Push (): – This function adds element to the end of an array

a b c

 

Pop (): – This function removes the last element of an array.

a b

c

Unshift (): – This function adds element to the beginning of an array.

a b c

 

Shift (): – This function removes the first element of an array.

b c

a

#! /usr/bin/perl

Create an array

@fighters = (“Rock”, “Cena”, “Kane”);

Print “Fighters List = @fighters \n”;

Output: Fighters List = Rock Cena Kane

Adding one element to the end of an array

push (@fighters, “Batista”);

Print “Fighters List = @fighters \n”;

Output: Fighters List = Rock Cena Kane Batista

Adding element at the start of an array

unshift (@fighters, “Goldberg”);

Print “Fighters List = @fighters \n”;

Output: Fighters List = Goldberg Rock Cena Kane Batista

Removing element from the end of an array

pop (@fighters);

Print “Fighters List = @fighters \n”;

Output: Fighters List = Goldberg Rock Cena Kane

Removing element from the start of an array

shift (@fighters);

Print “Fighters List = @fighters \n”;

Output: Fighters List = Rock Cena Kane

 

Adding/Removing elements from the middle of an Array

Splice () function is used for adding and deleting elements from the middle of an array. It adds elements anywhere in the array including at the beginning and end. Simultaneously, it can also remove ‘n’ numbers of element in a sequence from an array.

Splice @fighters, 2, 3, “Rikisi”, “Xerico”;

Here @fighters – Array to modify

2 – starting with 2nd element

3 – replace or remove 3 elements

“Rikisi”,” Xerico” — new elements to be added

  • Shift (@fighters) can also be written as splice @fighters, 0, 1;
  • Pop (@fighters) can also be written as splice @fighters, -1, 1;
  • An array with no element [ @fighters = ();] can be written as splice @fighters, 0;