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

Probably a stupid question, but from a style standpoint, and perhaps an efficiency standpoint, to do something as simple as print the contents of a list, is it prefrable to use map or foreach. Example:

while (my @fields = (getpwent)[6,7]) { map {print "$_\n"} @fields; print ("-" x 80); }
vs.
while (my @fields = (getpwent)[6,7]) { foreach my $item (@list) { print "$_\n"; } print ("-" x 80); }
Just curious..
Rich

Replies are listed 'Best First'.
Re (tilly) 1: map vs. foreach
by tilly (Archbishop) on Apr 25, 2001 at 07:39 UTC
    If you are not using the return, don't use a map.

    That said I would write your example as:

    while (my @fields = (getpwent)[6,7]) { print map "$_\n", @fields, ("-" x 80); }
    (print is quite happy taking a list...)
Re: map vs. foreach
by nardo (Friar) on Apr 25, 2001 at 07:07 UTC
    From a style standpoint, I consider foreach to generally be better than map. For this particular problem, I would use
    print join("\n", @fields), "\n";
    rather than a map or foreach.
Re: map vs. foreach
by hdp (Beadle) on Apr 25, 2001 at 07:39 UTC
    map in void? Are you trying to invoke merlyn's wrath? :) Consider also:
    while (...) { local ($, = $\ = "\n"); print @fields, "-" x 80; }
    This is hypothetically "less maintainable", as people may not be familiar with $, and $\; you've got to decide that for yourself.

    hdp.

    p.s. tilly's idea is better than mine.

Re: map vs. foreach
by Albannach (Monsignor) on Apr 25, 2001 at 07:27 UTC
    From an efficiency standpoint, I'm lead to believe there is a good reason not to use map in a void context - you're making Perl do a lot of work then you throw it away.

    --
    I'd like to be able to assign to an luser

Re: map vs. foreach
by jeroenes (Priest) on Apr 25, 2001 at 15:37 UTC
    I smell a use for supersplit here. These days it's also available on CPAN: SuperSplit!
    use SuperSplit; $pwd = supersplit_open( ':', '/etc/passwd' ); $pwd = [map [@$_[6,7]], @$pwd ]; #Or do you mean 5,6? print superjoin( "\n", $pwd ); #I'd leave the \n out
    chipmunk, is this a valid plug ;-)?

    Jeroen
    "We are not alone"(FZ)