tye has got it. Though I haven't benchmarked it, unpack is a very efficient method. Here's a disection:

$a = join ' ', unpack 'C*', $a;

That is roughly the same thing as:

@temparray = unpack 'C*', $a; $a = join ' ', @temparray;
The first part -- the unpack -- uses the template, 'C*', which reads like this: 'C' takes one byte and converts it to an unsigned char value (base 10). Note that per perldoc -f pack 'C' only works with byte-width characters. For Unicode you would probably use U, but that doesn't appear to be an issue in your case.

The asterisk in the unpack template basically just means to repeat that 'C' template for as long as there are more bytes to unpack into unsigned char values. So the result is that you get a list of unsigned char values (which happen to be the ASCII values) corresponding to the characters (the bytes) in the original string.

The next line -- the join line -- just serves to concatenate together the list of unsigned char values into one long string with each value separated from the next by a single space character (presumably so you have some prayer of knowing where one unsigned char value ends and the next one starts in the string).

In tye's example, the @temparray is avoided by just allowing unpack to spill its list of unsigned char values into the parameter list of join.


Dave


In reply to Re: Re: Converting ascii to numbers (unpack) by davido
in thread Converting ascii to numbers by toonski

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.