in reply to Using regex in Map function

You need to remember that the result of map is the list of the final value of each pass through its block. The value of s/// is a boolean indicating whether a replacement was made. You want the final value of the map block to be $_. Like so:

@new = map { s/$_/$_,hi/; $_ } <TEST>;

However, your substitution is less than ideal. In particular, you'll have problems if $_ contains any regex-special characters. If you're simply appending, you could do this:

@new = map { s/$/,hi/; $_ } <TEST>;
or, even betterworse, this:
@new = map { $_ . ',hi' } <TEST>;

A word spoken in Mind will reach its own level, in the objective world, by its own weight

Replies are listed 'Best First'.
Re^2: Using regex in Map function
by grinder (Bishop) on May 02, 2007 at 22:00 UTC
    The value of s/// is a boolean indicating whether a replacement was made.

    Err, no, not really. It's actually the number of replacements made. Thus:

    # given $x = 'abacad'; # then $x =~ s/a/z/; # returns 1 $x =~ s/a/z/g; # returns 3 $x =~ s/x/z/; # returns empty string, not undef

    ... although it can be treated quite nicely in a boolean manner :)

    • another intruder with the mooring in the heart of the Perl

Re^2: Using regex in Map function
by jettero (Monsignor) on May 02, 2007 at 21:14 UTC

    In addition to what jdporter is saying, I'd like to add that this is probably faster and clearer:

    @new = <TEST>; s/something/something/ for @new;

    I haven't Benchmarked it or anything, but I'm pretty sure it's faster than map {s/regex/stuff/} — either way, it's probably more readable.

    -Paul

Re^2: Using regex in Map function
by pKai (Priest) on May 02, 2007 at 21:21 UTC
    or, even better, this
    That may be subject to judgement.

    While your 1st and 3rd variant append behind the line-ending newline, the 2nd is probably closer to what the OP wanted, since $ is matching before that newline.

Re^2: Using regex in Map function
by strat (Canon) on May 03, 2007 at 09:57 UTC

    If you need something like the copy - do something more often, you could also create a copy-wrapper for map, let's call it cwmap:

    sub cwmap( &@ ) { map { local $_ = $_; # create copy $_[0]->(); # execute code-block $_; # copied element } @_[ 1..$#_ ]; # list } # cwmap # and then use it like map: @new = cwmap { s/$_/$_,hi/ } <TEST>;

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"