假设您在列表中设置了整数。
@lists = (22, 10, 5, 2);
但是如果我确实希望所有的元素都分为2代表,那么除了在运行循环中手动计算之外还有其它方法吗?
foreach $list (@lists)
{
print (list/2);
}
答案 0 :(得分:6)
my @numbers = (22, 10, 5, 2);
# Create a new list, as in David Dorward's answer.
my @halves = map { $_ / 2 } @numbers;
# Or modify the original list directly.
$_ /= 2 for @numbers;
答案 1 :(得分:5)
@lists = [22, 10, 5, 2];
应该是
@lists = (22, 10, 5, 2);
然后你可以
@lists = map { $_ / 2 } @lists