[EMAIL PROTECTED] (Sean Carte) wrote:
>At 11:38 am +0900 9/4/01, Nobumi Iyanaga wrote:
>>
>>$str = "aiueokakikukeko";
>>$to_find = "aiueo";
>>$replace_with = "hijkl";
>>$str =~ tr/$to_find/$replace_with/;
>>print $str, "\n";
>
>#!/usr/bin/perl -w
>use strict;
>
>my $str = "aiueokakikukeko";
>my $to_find = "aiueo";
>my $replace_with = "hijkl";
>$str =~ tr/$to_find/$replace_with/;
>print $str, "\n";
>
>prints: aaueekakakukeke

Look a little more closely...

You replaced '$' with '$',
             't' with 'r',
             'o' with 'e',
             '_' with 'p',
             'r' with 'l',
             'e' with 'a',
             ...

Variable interpolation doesn't happen in tr.  It's necessary to either
use s///g or eval.

>So I suppose the answer is yes, though I suspect you'd probably want 
>to substitute rather than translate:
>
>$str =~ s/$to_find/$replace_with/;
>....
>prints:  hijklkakikukeko

That's not right either, it only replaced instances of the entire string
"aiueo".  You may mean:

   my $str = "aiueokakikukeko";
   my $to_find = "aiueo";
   my $replace_with = "hijkl";
   my %charmap = map {substr($to_find,$_,1), substr($replace_with,$_,1)}
                 0..length($to_find)-1;
   $str =~ s/([$to_find])/$charmap{$1}/g;
   print $str, "\n";
   ...
   prints:  hijklkhkikjkkkl


But it's easier (and perhaps faster) to use eval("tr/$to_find/$replace/").

  -------------------                            -------------------
  Ken Williams                             Last Bastion of Euclidity
  [EMAIL PROTECTED]                            The Math Forum

Reply via email to