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


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;


      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] } [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 { $_->[0] + $_->[1] } 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] ); $result = $x->add( $y ); print $result; # 5.00000 7.00000 9.00000
Re: array assignment
by Anonymous Monk on Nov 13, 2004 at 18:41 UTC
    Thank you guys, all the suggestions were very interesting. Esp. mapcar was - yes, cool!

    Inspired with what I've learnt here I contribute with a variation

    my ($dd, $mm, $yyyy) = map { $_->[0], $_->[1] + 1, $_->[2] + 1900 } ([ +(localtime)[3..5]]);
Re: array assignment
by TedPride (Priest) on Nov 12, 2004 at 19:50 UTC
    That's cheating. No, I don't think there is a way to do it.