Xu Wang
Xu Wang

Reputation: 10597

How can I print a character in octal in Perl?

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.

Upvotes: 2

Views: 2067

Answers (1)

hobbs
hobbs

Reputation: 240254

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".

Upvotes: 8

Related Questions