Re: int to ascii
by myocom (Deacon) on May 08, 2001 at 02:53 UTC
|
What you want is the chr function, though you'll need to give it an offset so that 1=a, etc.
my @message=(8,5,12,12,15);
print map(chr(96+$_),@message); # Change the 96 to 64 for uppercase
| [reply] [d/l] |
(Ovid) Re: int to ascii
by Ovid (Cardinal) on May 08, 2001 at 02:55 UTC
|
Something like the following? :)
perl -e "print chr( 2**6 + $_ ) foreach qw/ 15 54 41 36 /"
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. | [reply] [d/l] |
Re: int to ascii
by asiufy (Monk) on May 08, 2001 at 02:54 UTC
|
No, since Perl is not a strongly typed language! :)
What you have to do, though, is first convert the character 'a' into its ASCII value, using the ord() function. Then you can add your integer to the resulting value, and to obtain the character again, you use the chr function.
Here's a sample:
$first = ord("a");
for (my $x=0; $x < 10; $x++)
{
print chr($first+$x). " ";
}
That will print :
a b c d e f g h i j
Hope it helps...
| [reply] [d/l] [select] |
|
|
| [reply] |
Re: int to ascii
by arturo (Vicar) on May 08, 2001 at 02:58 UTC
|
Oh, what the heck, just for fun:
my %int_to_char;
@int_to_char{ 1 .. 26} = (a..z);
# get @array
my @chars = map { $int_to_char{$_} } @array;
If only because it promises to handle differences in locale nicely ...
(mondo inefficient, too =)
| [reply] [d/l] |
Re: int to ascii
by stephen (Priest) on May 08, 2001 at 02:55 UTC
|
You need to take a look at the ord, pack, and chr functions. (Look at the first example for 'pack').
map may also fit into your solution someplace. Hint hint. :)
You don't need to typecast it. Perl is a loosely-typed language. There is no syntax to typecast things in Perl.
stephen
| [reply] |
|
|
The following program does indeed print out 'ABCD':
use strict;
my $foo = pack("cccc",65,66,67,68);
print $foo;
What I do not understand is why it works. Page 757 of Camel3 says that pack "takes a LIST of ordinary Perl values and converts them into a string of bytes."
Now who says that "A" is a byte? Maybe my operating system uses Unicode and "A" is two bytes. Isn't ASCII a 7-bit encoding scheme? (A byte is eight bits, not 7.)
So why do the bytes that pack returns necessarily print out as 'ABCD' and not as gibberish?
| [reply] [d/l] |
|
|
Yes, who said that 'A' is a byte? 'A' is merely the ASCII representation of the byte 0x41. If you were using a different character set, then print pack("cccc",65,66,67,68) could very well produce different output.
| [reply] [d/l] |
Re: int to ascii
by Daddio (Chaplain) on May 08, 2001 at 04:10 UTC
|
my @var = ('','a'..'z');
print "$var[$_] " for (1,2,3,10);
Simple, but somewhat effective. Just don't forget to pad the array so the integers line up; otherwise you'll have to use $var[$_ - 1].
--
D
a
d
d
i
o
| [reply] [d/l] [select] |