How to Use the Chr() and Ord() functions in Perl

Computer programming illustration

 

elenabs/Getty Images

The Perl programming language's chr() and ord() functions are used to convert characters into their ASCII or Unicode values and vice versa. Chr() takes an ASCII or Unicode value and returns the equivalent character, and ord() performs the reverse operation by converting a character to its numeric value. 

Perl Chr() Function

The chr() function returns the character represented by the number specified. For example:

#!/usr/bin/perl

print chr (33)

print "/n";

print chr (36)

print "/n";

print chr (46)

print "/n";

When this code is executed, it produces this result:

!

$

&

Note: The characters from 128 to 255 are by default not encoded as UTF-8 for backward compatibility reasons.

Perl's Ord() Function

The ord() function does the opposite. It takes a character and converts it into its ASCII or Unicode numeric value.

#!/usr/bin/perl

print ord ('A');

print "/n";

print ord ('a');

print "/n";

print ord ('B');

print "/n";

When executed, this returns:

65

97

66

You can confirm the results are accurate by checking an ASCII Code Lookup Table online.

About Perl

Perl was created in the mid-'80s, so it was a mature programming language long before websites exploded in popularity. Perl was originally designed for text processing, and it is compatible with HTML and other markup languages, so it quickly became popular with website developers. Perl's strength lies in its ability to interact with its environment and its cross-platform compatibility. It can easily open and manipulate many files within the same program. 

Format
mla apa chicago
Your Citation
Brown, Kirk. "How to Use the Chr() and Ord() functions in Perl." ThoughtCo, Aug. 28, 2020, thoughtco.com/perl-chr-ord-functions-quick-tutorial-2641190. Brown, Kirk. (2020, August 28). How to Use the Chr() and Ord() functions in Perl. Retrieved from https://www.thoughtco.com/perl-chr-ord-functions-quick-tutorial-2641190 Brown, Kirk. "How to Use the Chr() and Ord() functions in Perl." ThoughtCo. https://www.thoughtco.com/perl-chr-ord-functions-quick-tutorial-2641190 (accessed March 28, 2024).