convert a string into another string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bazsi8304
    New Member
    • Mar 2013
    • 2

    convert a string into another string

    Hello!

    I'd like to convert a string like this in perl:

    example :
    original string = 333445566
    result string = 0x33,0x44,0x55, 0x66
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    I don't know perl so someone else will have to help you with the code but what happened to the third "3"? Why did it get dropped?

    Comment

    • sathishkumar se
      New Member
      • Dec 2011
      • 10

      #3
      Explain clear about your requirement

      Comment

      • bazsi8304
        New Member
        • Mar 2013
        • 2

        #4
        I've made a mistake.The 3rd "3" is only a typo.
        original string = 33445566
        result string = 0x33,0x44,0x55, 0x66

        So I need a script in perl which converts a string (with arbitrary length)into a string what I showed in result string.
        This has to do the next :

        1.create an array
        2.insert "0x" before each element of the array and insert ","after each element of the array

        Comment

        • Rabbit
          Recognized Expert MVP
          • Jan 2007
          • 12517

          #5
          What do you have so far?

          Comment

          • peoff
            New Member
            • Mar 2013
            • 1

            #6
            Hi,
            Maybe that is what you are looking for:

            Code:
            # data
            $original_string = "33445566";
            
            # test
            my $result_string = my_convert($original_string);
            print $result_string;
            
            # the function for string modification
            sub my_convert(){
                my $var = shift;
                my $new_str = "";
                foreach ( $var =~ /.{2}/sg){
                    $new_str .= "0x$_,";
                }
                chop($new_str);
                return $new_str;
            }
            notes:
            1. Source string should be divisible by 2, so if you have string something like this "11223" => result will be "0x11,0x22" . As you see "3" is skipped.
            2. In your comments you talk about an array, so if you want to work with the array, you can modify code inside "foreach".

            Comment

            • RonB
              Recognized Expert Contributor
              • Jun 2009
              • 589

              #7
              Code:
              $, = ',';
              my $str = '3344556';
              my @parts;
              push @parts, "0x$1" while $str =~ /(..?)/g;
              
              print @parts;

              Comment

              Working...