http://www.perlmonks.org?node_id=407478

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

After doing things like
```my (\$dd, \$mm, \$yyyy) = (localtime)[3..5];
\$mm += 1;
\$yyyy += 1900;
I start wondering if there are any array assignment "tricks" to assign and modify in one fell swoop. For instance to add the elements of two arrays to each other
```fake code:
@result = (1,2,3) + (4,5,6);
# intending @result to contain (5,7,9)
or in a similar fashion concat the elements...

Thanks for any insights

L

Replies are listed 'Best First'.
Re: array assignment
by kvale (Monsignor) on Nov 12, 2004 at 19:59 UTC
map makes this easy:
```@a = (1,2,3);
@b = (4,5,6);
@result = map {\$a[\$_]+\$b[\$_]} 0..\$#a;

-Mark

Applying that to the date problem:
```my (\$dd, \$mm, \$yyyy) = map {(0,1,1900)[\$_] + ((localtime)[3..5])[\$_]}
+0..2;
Not real pretty, but I guess that's why Tye invented Mapcar, which, if I read the docs right, one could use to solve the problem thus:
```my (\$dd, \$mm, \$yyyy) = mapcar { \$_ + \$_ } [0,1,1900], [(localtim
+e)[3..5]];
(no extra map needed, Dragonchild).

Caution: Contents may have been coded under pressure.
Re: array assignment
by dragonchild (Archbishop) on Nov 12, 2004 at 19:50 UTC
In your specific case, I would use something like Date::Calc to handle the uglies. Or, you could write a function that wraps that. :-)

As for the coolness factors ... you could use mapcar -- map for more than one list. That way, you might end up with something like:

```my (\$dd, \$mm, \$yyyy) =
map {
\$_-> + \$_->
} mapcar(
[(localtime)[3..5]],
[0, 1, 1900],
);

Of course, you now have to explain how mapcar works and ... well, maybe it's too cool. :-)

Being right, does not endow the right to be rude; politeness costs nothing.
Being unknowing, is not the same as being stupid.
Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Re: array assignment
by fglock (Vicar) on Nov 12, 2004 at 19:32 UTC

PDL and Math::Matrix can do that:

```use Math::Matrix;

my \$x = new Math::Matrix ( [1,2,3] );
my \$y = new Math::Matrix ( [4,5,6] );

print \$result;

#    5.00000    7.00000    9.00000
```my (\$dd, \$mm, \$yyyy) = map { \$_->, \$_-> + 1, \$_-> + 1900 } ([