Can you explain the difference between a for loop and a foreach loop in Perl?

In Perl, both for and foreach loops are used to iterate over a set of values. The main difference between them is in how they are used.

A for loop is used to iterate over a range of numbers, specified by a start and end value. The loop variable is incremented on each iteration, and the loop continues until the loop variable reaches the end value. The syntax for a for loop is:

for (initialization; condition; increment) { # code to be executed }

For example, this for loop will print the numbers from 1 to 10:
for ($i = 1; $i <= 10; $i++) { print "$i\n"; }

A foreach loop, on the other hand, is used to iterate over the elements of an array or a hash. The loop variable is set to each element of the array or hash in turn, and the loop continues until all elements have been processed. The syntax for a foreach loop is:
foreach my $variable (@array) { # code to be executed }

For example, this foreach loop will print the elements of an array:
@fruits = ("apple", "banana", "orange"); foreach my $fruit (@fruits) { print "$fruit\n"; }

In summary, the for loop is used to iterate over a range of numbers and the foreach loop is used to iterate over the elements of an array or a hash. While for loop allows you to specify the initial value, end value, and increment, foreach loop allows you to iterate over the elements of an array or hash directly.