http://www.perlmonks.org?node_id=932305


in reply to map and regexp. An newbie question

Within map, $_ is an alias to each array element (one per iteration). So if you modify $_, you modify the array element to which it is aliased for a given iteration.

The s/// operator is returning the number of times it matched. But what you seem to want is not the number of times, but the actual substitution. And you also want that to not affect the key.

my %hash = map{ my $temp = $_; $temp =~ s/a/X/g; $_, $temp } @array;

This snippet works by making a copy of the current element, then doing the substitution on that copy, and finally, returning both the original (which becomes a key) and the modified version (which becomes a value).


Dave

Replies are listed 'Best First'.
Re^2: map and regexp. An newbie question
by anneli (Pilgrim) on Oct 19, 2011 at 06:56 UTC

    If you're using a more recent Perl, you can use the /r option to s///:

    my %hash = map {$_, $_ =~ s/a/X/gr} @array;

      Did you try that?

      The /r modifier (Perl 5.14) only solves one of the problems (it doesn't alter the original). It doesn't solve the second problem that the $_ =~ s/a/X/gr construct is not being evaluated in list context, and therefore returns the number of substitution matches, not the modified string.

      Apparently I didn't. ;) -- lousy excuse in a followup node below.


      Dave

        No, but I got lucky! See perlop:

        If the /r (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when /r is used. The copy will always be a plain string, even if the input is an object or a tied variable.

        This applies even when /g is being used (otherwise what use would /r be, being that it's non-destructive?).

        (Edit: to clarify, no, I didn't try it, but I did upon being chastened, found that it did work, and ran to docs to find out why!)

      I knew that having an assignment operation, the behavior of Perl was logical ... But I was sure, also, that there was a way to get it simple and transparent ...Thank you, anneli!

Re^2: map and regexp. An newbie question
by nando (Acolyte) on Oct 19, 2011 at 15:31 UTC

    Thank you, Dave! Yes, you've come to understand my problem despite my incompetence with English ( and the contributions of Google Translate...) :)