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

Greetings council, I have a problem, which is probably just a trivia question to you guys:

This works:

my %fruitcolors = ( banana=>"yellow" ); $_ = "applebananachocolate"; s/apple(banana)chocolate/$fruitcolors{$1}/ie;
But this doesn't:
s/(apple)(banana)(chocolate)/$1$fruitcolors{$2}$3/ie;
Is there a special delimiter I need?

Thanks in advance

=~Desertcoder

Edit Masem 2002-01-21 - Changed title from "Expressionless :"

Replies are listed 'Best First'.
Re: Expressionless :
by japhy (Canon) on Jan 20, 2002 at 23:48 UTC
    The /e modifier is not useful here. Remove it. That's what's giving you trouble. If you needed to execute code, then it would be useful. Not here.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Expressionless :
by belg4mit (Prior) on Jan 20, 2002 at 23:24 UTC
    With /e the second half of s/// is an expression, you must manually concatenate your variables. The first works because there is no need to concatenate a single variable (to what?!). It's an easy enough mistake to make.

    UPDATE: Note I explicitly did not say use . because you only need effect a concatenation. TIMTWOTDI, you could also use an interpolating quote.

    --
    perl -pe "s/\b;([st])/'\1/mg"

      Doh! I should have known that. Thanks for your rapid response. =~Desertcoder
Re: Expressionless :
by blakem (Monsignor) on Jan 20, 2002 at 23:39 UTC
    For this particular regex, you could rewrite it using a look-ahead and look-behind assertion....
    s/(?<=apple)(banana)(?=chocolate)/$fruitcolors{$1}/i;
    Seems a bit better than replacing pieces with identical copies of themselves.....

    Update: removed superfluous /e that japhy points out below

    -Blake

Re: Expressionless :
by dws (Chancellor) on Jan 20, 2002 at 23:30 UTC
    When asking for help on problems like this, it helps to also include the error message you're getting from Perl.

    The /e modifier says to treat the right-hand side of the substitution as an expression. But   $1$fruitcolors{$2}$3 isn't a valid Perl expression. To make it valid, add string concatenation operators, as follows:   s/(apple)(banana)(chocolate)/$1 . $fruitcolors{$2} . $3/ie;