Bootstrap FreeKB - Perl (Scripting) - Append element to the end of an array (push)
Perl (Scripting) - Append element to the end of an array (push)

Updated:   |  Perl (Scripting) articles

Let's say you have an array of fruit that contains apple, banana, orange, and grape.

my @fruits = qw(apple banana orange grapes);

 

Push can be used to add values to the end of an array. In this example, pineapple is added to the fruits array.

push @fruits, 'pineapple';

 

If pineapple is in a variable, do not use the single quotes.

push @fruits, $pineapple;

 

The array can be printed.

print @fruits;

 

Printing the array will show that "pineapple" has been appeneded to the end of the array.

apple banana orange grape pinnapple

 

The following if statement can be used to not append a value to the array if the array already contains the value. In this example, if the @fruits array does not contain "strawberry" then strawberry will be appended to the array.

if (not grep(/strawberry/, @fruits)) {
  push @fruits, "strawberry";
}

 

Unshift can be used to append values to the beginning of an array.

Pop can be used to remove values from the end of an array.

Shift can be used to remove values from the beggining of an array.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a2d86a in the box below so that we can be sure you are a human.