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

I recently ran into an issue where I needed to convert each character in a string to an ASCII value, is there a simple way of doing this in perl ?

Thanks, YpCat
  • Comment on How do I convert each character in a string to its ASCII value ?

Replies are listed 'Best First'.
Re: How do I convert each character in a string to its ASCII value ?
by loc (Beadle) on Sep 21, 2001 at 13:40 UTC
    From the Perl Cookbook:
    Use pack and unpack. Here is an example (recipe 1.4):
    @ascii_character_number = unpack( "C*", "sample" ); print "@ascii_character_number\n"; #prints 115 97 109 112 108 101 $word = pack( "C*", @ascii_character_numbers ); $word = pack( "C*", 115, 97, 109, 112, 108, 101 ); # same print "$word\n"; #prints sample

    -loc

Re: How do I convert each character in a string to its ASCII value ?
by jmcnamara (Monsignor) on Sep 21, 2001 at 13:44 UTC

    The pack/unpack example shown above is a better methodology but you can also do it like this:
    my @ascii = map { ord } split //, $string;


    John.
    --

Re: How do I convert each character in a string to its ASCII value ?
by ChOas (Curate) on Sep 21, 2001 at 13:43 UTC
    Hi!
    #!/usr/bin/perl -w use strict; my $String="This is Ascii"; $String=~s/(.)/ord($1)/eg; print "Ascii: $String\n";

    p.s. Might not be the best answer offered here, but it answers your question to the fullest ;)

    GreetZ!,
      ChOas

    print "profeth still\n" if /bird|devil/;
Re: How do I convert each character in a string to its ASCII value ?
by John M. Dlugosz (Monsignor) on Sep 22, 2001 at 01:22 UTC
    Try this:
    printf "%vd", "This is a test";
    simple enough?