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

Dear Monks

I would like to do something like:
$a = 'a b c d' ; $b = 'rstu' ; for ($a) { s/a/substr($b,0,1)/ ; s/b/substr($b,1,1)/ ; ..... }
Somehow substr is seen as a string, how do change this behaviour ?

Thanks a lot
Luca

Replies are listed 'Best First'.
Re: regexp and a perl function
by davorg (Chancellor) on Feb 27, 2006 at 15:51 UTC

    You've already got a couple of answers explaining the /e option to s///, but I wonder if that's really the best approach. Perhaps you should look at using tr/// instead of s///.

    $a = 'a b c d'; $a =~ tr/abcd/rstu/; print $a;
    --
    <http://dave.org.uk>

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

Re: regexp and a perl function
by borisz (Canon) on Feb 27, 2006 at 15:38 UTC
    s/a/substr($b,0,1)/e ; s/b/substr($b,1,1)/e ;
    Boris
Re: regexp and a perl function
by mickeyn (Priest) on Feb 27, 2006 at 15:38 UTC
    use the modifier 'e' on your regex ....

    s/a/substr($b,0,1)/e ; s/b/substr($b,1,1)/e ;

    (definition:) it evaluates the right hand side of s/// as an expression .

    Enjoy,
    Mickey

Re: regexp and a perl function
by duff (Parson) on Feb 27, 2006 at 15:56 UTC

    If you're just changing one set of characters into another set of characters rather than utilizing the full power of the regular expression engine, you might just want to use the transliteration operator tr///

    # turn all of the "a" characters into "r"s and all of the "b"s into "s +"s, etc. $string =~ tr/abcd/rstu/;

    See perlop for more info on tr///