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

I have a 32 bit binary number (created with the dec2bin subroutine found here) and I need to create a new string out of it. I need to replace all the 1's with H and all the 0's with L's. For instance 1001 needs to be converted to HLLH. I tried $newstring=~ s/0/L; $newstring=~ s/1/H; but this only replaces the first character of the binary string. This is probably simple but I'm new to perl and can't find a solution in my perl book. Thanks.

Replies are listed 'Best First'.
Re: substitution
by broquaint (Abbot) on Dec 06, 2001 at 21:01 UTC
Re: substitution
by impossiblerobot (Deacon) on Dec 06, 2001 at 21:03 UTC
    I probably won't be the first to suggest this, but this is a perfect use for the tr/// function:
    $newstring =~ tr/01/LH/;
    which translates all 0's to L's and 1' to H's.

    Your substitutions would also work by using the 'g' global option at the end, which causes it to substitute every match, not just the first one:
    $newstring =~ s/0/L/g; $newstring =~ s/1/H/g;
    I hope this helps.

    Impossible Robot
Re: substitution
by hotshot (Prior) on Dec 06, 2001 at 20:57 UTC
    use the flag g at the end of the regexp
    $newstring =~ s/0/L/g; # will substitute every appearence of 0 with +L


    Hotshot