in reply to Applying regex to array

You could use map:
my @fields = qw/this that the_other/; map { s/^|$/"/g; } @fields;

Replies are listed 'Best First'.
Re^2: Applying regex to array
by davorg (Chancellor) on Nov 24, 2004 at 10:38 UTC

    Using map in a void context is bad. Perl expects map to return a list, so it wastes time building up a return list which just gets thrown away. I've heard figures that show it to be 10% slower.

    I'd just use for.

    s/^|$/"/g for @fields;

    I understand this is being worked on for new versions of Perl. There's no reason why map can't work out that it's being called in void context and not build up the return list.

    Update: You can safely ignore this advice if you're using Perl 5.8.1 or greater (see perl581delta). Personally, I still think it's an abuse of map when foreach can be used to do the same thing. But YMMV :)

    Update (again): Limbic~Region points me at this previous discussion of these points (particularly Abigail's reply here. Having read it thru, it seems to me that tilly sums up my point of view pretty well.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      Personally, I still think it's an abuse of map when foreach can be used to do the same thing. But YMMV :)

      I used to think that, but it's such a common thing to be suggested that I think it's worth asking why. Actually, I also think I have an answer. This paper on natural programming languages has some interesting things to say about how people naturally think about solving problems:

      Aggregate operators (acting on a set of objects all at once) were used much more often than iterating through the set and acting on the objects individually. For example, "Move everyone below the 5th place down by one."

      While one can argue the meaning of this, this and the rest of the paper suggested to me that programming in a way that matches how people (not necessarily just programmers) think is more likely to produce good code. The paper is an interesting read.

      Cheers,
      Ovid

      New address of my CGI Course.

      I started to reply to this before I read the last paragraph, but I may as well keep going. I thought map in void context had already been optimised in the newest versions. That's what I'd heard, anyway.

        Ah yes. Fixed in perl 5.8.1 - according to this.

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg