First, there is an easy way to generate consecutive integers, using the ..
operator. So
@a = (1..10);is the list
@a = (1,2,3,4,5,6,7,8,9,10);(You can also do this for letters, so
('a'..'d')
is the same as ('a','b','c','d')
.)
There is also a command called map
that takes a code block and an array and performs the code on each element of the array. Within the code, the variable $_
refers to the array element. So
@x = map {.5*$_} (1..20);produces the same
@x
as Gavin's code more efficiently (but harder to read for those not familiar with map
).
There is also a looping command foreach
that is similar to a for
loop, but instead of giving an initial condition, a termination test, and an increment function, you give it an array and it runs the variable through that array. This is similar to map
, but you get to specify the name of the loop variable. So, for example, you could do
@x = (); foreach $i (1..20) { push(@x,.5*$i} }This can sometimes make your loops easier to specify. Note that this works for any array, with any type of entry, so
foreach $c ('a'..'d') { ... do something with $c ... }would let you loop through the letters
a
through d
. Similarly, if you have an array @a
and want to do something to the entries in the array, use
foreach $x (@a) { ... do something with $x ... }In situations where you don't actually need to index into the array, this can be very helpful. Also, note that if you set the value of
$x
within the loop, that will change the value within @a
as well, so this is a way of modifying the entries in @a
one at a time. Also very useful at times.