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

Normally this would be extremely easy. Really, this isn't that tough I just need to know a few things. I have an array of characters I want to translate a string to character by character. Perl, by default, does things string by string if I am correct. I know I can change that using either the $/ or $, operators. Which one should I use?

Now once I get that down, I can throw that string into a loop comparing character by character...$_ against the characters I need to convert to. The question is that how do I set the $/ or $, to recognize only a character? My guess is that I can regex the operator,

e.g. $/ =~ /\w/;.

Is this the right way to do it? Is there a better way?

TIA

----------
- Jim

Replies are listed 'Best First'.
Re: character conversion in a loop...
by John M. Dlugosz (Monsignor) on Aug 05, 2001 at 22:44 UTC
    Three ways to go character-by-character:

    use split ('', $string) to return an array of characters.

    use s/./g as the condtional of a while loop to match each character.

    use substr for (1..length).

    —John

      I think you munged your second suggestion (which is the one I typically use) I believe you meant.

      /(.)/g

      As in:

      while($string =~ /(.)/g) { my $letter = $1; .... }

      -Blake

        It works: Without the parens, you can use $&, rather than $1 as you showed.

        —John

      Hmm...so my way wouldn't have worked eh? So much for innovativeness.

      ----------
      - Jim

        Right, because “Remember: the value of $/ is a string, not a regex. awk has to be better for something. :-)”

        However, you could set it to an integer to read one character at a time.

        —John

Re: character conversion in a loop...
by bwana147 (Pilgrim) on Aug 06, 2001 at 02:31 UTC

    Did you ever have a look at the transliteration operator tr? If the array of chars you are translating is dynamic, you might want to use it in an eval:

    $from = 'abcdef'; $to = 'ghijkl'; eval qq{ tr/$from/$to/ };

    --bwana147