The below will print “Hello!” 10 times:
for ($i = 0; $i < 10 ; $i++){ print "Hello!n"; }
Output: Hello!
For iterating through an array it can be handy to use a foreach loop. In the example below the foreach loop will access each variables in the array and allow you to use it as $i:
@array = ('one','two','three');
foreach $i (@array) { print "$i, "; }
Output: one, two, three,
To create a new array it is as simple as declaring it as shown below. This method can also be used to clear an existing array, though you will have to drop the my.
my @array = ();
To create a new array with elements just declare the array with a comma delimited list in brackets after it.
my @array = (hendrix,santana,young,clapton);
In this example we will add new elements to an array using the push() function. To do this we will use a loop to push elements from an existing array @array into our new array cleverly named…@newarray. The variable $item represents the value of the currently accessed element in @array
my @array = (hendrix,santana,young,clapton);
my @newarray = ();
foreach my $item (@array) {
push( @newarray,$item);
}