2

How can I print characters with their octal representations? Note that these characters might be special characters (escapes, backscapes, arrow keys, etc.).

For example, I would like a function 'printoctal', such that:

my $char = 'P';
printoctal $char;

And I would like that to print 120.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Xu Wang
  • 10,199
  • 6
  • 44
  • 78

1 Answers1

8

You want two things: ord takes a string, and returns the numeric value of that string's first character. That is, ord "P" is 80.

Then, you want printf or sprintf. sprintf "%o", $num will take a number and return a string that is the octal representation of that number, printf will print the octal representation instead of returning it.

Together, printf "%o\n", ord "P" will print "120".

hobbs
  • 223,387
  • 19
  • 210
  • 288