Yoon Lee
Yoon Lee

Reputation: 2039

Compute all element in integer list

let's say you have set of integer in the list.

List Declare:

@lists = (22, 10, 5, 2);

but if I do want all the elements to be divide in let's say 2, is there anyways to do other than manually computing in running loop?

Don't want to compute like this:

foreach $list (@lists)
{
    print (list/2);
}

Upvotes: 1

Views: 106

Answers (2)

FMc
FMc

Reputation: 42421

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;

Upvotes: 6

Quentin
Quentin

Reputation: 944159

@lists = [22, 10, 5, 2];

should be

@lists = (22, 10, 5, 2);

then you can

@lists = map { $_ / 2 } @lists

Upvotes: 5

Related Questions