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

Why my code below:
$ perl -MData::Dumper -e ' @arr = ("A[TCG]GG 3", "CTG[AA] 4"); @nar = map { #get rid of trailing number my $st = (split(" ",$_))[0]; #replace bracket with S $st =~ s/\[[ATCG]+\]/S/g; } @arr; print Dumper \@nar '
doesn't produce this:
$VAR1 = [ 'ASGG', 'CTGS' ];

Regards,
Edward

Replies are listed 'Best First'.
Re: Multiple Transformations with "map"
by davido (Cardinal) on Nov 26, 2005 at 07:43 UTC

    map returns the value of the last expression evaluated within { #block }. The last expression you're evaluating is a substitution operator, and its value is a boolean value; true (1) if a match occurred, or false if there was no match. That's why it keeps passing '1' into @nar. If you want to return the result of the substitution, make sure that value is the last thing evaluated in { #block }.

    @nar = map { # get rid of trailing number my $st = ( split( " ", $_ ) )[0]; # replace bracket with S $st =~ s/\[[ATCG]+\/S/g; # return result value $st; } @arr;

    ...that ought to do it...


    Dave

      The last expression you're evaluating is a substitution operator, and its value is a boolean value; true (1) if a match occurred, or false if there was no match.

      If a match occurs, the substitution operator returns the number of substitutions made, not simply 1 (unless that happens to be the number of substitutions made... as in this case.)

      -sauoq
      "My two cents aren't worth a dime.";
      
Re: Multiple Transformations with "map"
by TedPride (Priest) on Nov 26, 2005 at 15:15 UTC
    I personally never liked map. for works just as well in almost all situations, and it's much easier to understand.
    my @arr = ("A[TCG]GG 3", "CTG[AA] 4"); for (@arr) { s/ .*//; s/\[[ATCG]+\]/S/g; } print join "\n", @arr;