[LA.pm] String handling like C array

Don Armstrong don at donarmstrong.com
Fri Feb 3 14:47:16 PST 2006


On Fri, 03 Feb 2006, Robin Rowe wrote:
> I often walk through strings as arrays in C, an idiom something like 
> this contrived example:
> 
> void SwapXY(char* string)
> {  char* ptr=string;
>     while(*ptr)
>     {  const char c=*ptr;
>        if('x'==c)
>        {  *ptr='y';
>        }
>        else if('y'==c)
>        {  *ptr='x';
>        }
>        ptr++;
>     }
> }
> 
> In Perl would I walk the string using substr and length or is there
> a better way to do array-level string manipulation?

This sounds like you want:

$string = tr/yx/xy/;

FE:

perl -le '$string=q(fob); $string =~ tr/ofb/abr/; print $string'

In general, doing array-level string manipulation is rarely required;
the times that you may think you need it tr///, s///, split, or m//
are probably better choices.


Don Armstrong

-- 
She was alot like starbucks.
IE, generic and expensive.
 -- hugh macleod http://www.gapingvoid.com/batch3.htm

http://www.donarmstrong.com              http://rzlab.ucr.edu


More information about the Losangeles-pm mailing list