I am trying to loop through the products array and create a new variable for each item in products.
While it is possible to create a new variable for each item, it's a bad idea. They have to be global, the syntax is ugly, and it's difficult to pass those variables around as a collection. Instead, use a hash or an array. In this case, since your items are indexed by number and there's no gaps an array makes the most sense.
my @product_params;
foreach my $product (@products) {
push @product_params, param($product);
}
For each $product
in @products
, it will add param($product)
to @product_params
. For example, the parameter for $products[5]
is stored in $product_params[5]
.
Since this is a one-to-one mapping of @products
to its parameters, its easier and faster to do the above with a map
. A mapping runs each element of a list through a function to create a new list. $_
contains each element of @products
in turn.
my @product_params = map { param($_) } @products;