in reply to using map with compound code blocks to alter strings: a strange result

I would narrow the selection down first with grep, then transform:
$ perl -l use strict; use warnings; my @strings = qw(boy bird FALSE); @strings = map { qq{"$_"} } grep( !/FALSE/, @strings); print join (q{,}, @strings); __END__ "boy","bird" $
Update:As kyle points out, this solution is both wrong and inefficient.
--
print map{chr}unpack(q{A3}x24,q{074117115116032097110111116104101114032080101114108032104097099107101114})
  • Comment on Re: using map with compound code blocks to alter strings: a strange result
  • Download Code

Replies are listed 'Best First'.
Re^2: using map with compound code blocks to alter strings: a strange result
by kyle (Abbot) on Jun 15, 2007 at 18:07 UTC

    The problem with this is that the OP said that the desired result is a list that includes every element in the original list. Some will be transformed and some won't.

    Another problem is more subtle. When you grep first and then map, you loop over the list twice. If it's a very long list, this will often be a waste of time. The only time I'd want to do it is if I expect grep is going to remove a lot of the list and/or the map's work is especially time consuming. In most other cases, it's better to make the decisions in the map only.

    Even when you want to remove elements, you can have the map block return () for the elements to remove. The code you wrote could look like this:

    my @strings = qw(boy bird FALSE); @strings = map { /FALSE/ ? qq{"$_"} : () } @strings; print join q{,}, @strings;

    It does the same thing, but it's only one loop.