Perl ord() function

In the Perl programming language has a built-in function ord(). This function returns the number that corresponds to a specified symbol.

Here's an example:

▶ Run
#!/usr/bin/perl

use utf8;
use feature qw(say);

say ord('A'); # 65
say ord('1'); # 49
say ord('Ж'); # 1046

Arguments

If the functions ord() do not pass any arguments, the function works with default variable $_:

▶ Run
#!/usr/bin/perl

$_ = 'a';

print ord(); # 97

Standard use of this function is to give her exactly one character. In this case, the function will return the numeric value of this symbol. If the functions ord() to pass a string consisting of several characters, the function will return the numeric value of the first character:

▶ Run
#!/usr/bin/perl

use feature qw(say);

say ord('a'); # 97
say ord('abcdef'); # 97

If the functions ord() pass more than one argument, it will error:

▶ Run
#!/usr/bin/perl

print ord('a', 'b', 'c');
Too many arguments for ord at script.pl line 3, near "'c')"
Execution of script.pl aborted due to compilation errors.

In the case if you pass in ord() is the empty string, the function will return the number 0:

▶ Run
#!/usr/bin/perl

print ord('');

Unicode

Here is a sample program in which the same symbol a function ord() returns a different value:

▶ Run
#!/usr/bin/perl

use feature qw(say);

say ord('Ъ');

use utf8;

say ord('Ъ');

The program will display:

208
1066

The first call ord('Ъ') returns the number 208. This happens due to the fact that ord() taking its argument as a single character, but as a string of two bytes 208 170 and returns a number for the first character of this string.

But after use utf8; perl thinks your code is encoded utf8 and ord() takes its argument as a string of two characters and as a string of a single character. And returns the value 1066.

Official documentation

Here is the output of the command perldoc -f ord:

    ord EXPR
    ord     Returns the numeric value of the first character of EXPR. If
            EXPR is an empty string, returns 0. If EXPR is omitted, uses $_.
            (Note *character*, not byte.)

            For the reverse, see "chr". See perlunicode for more about
            Unicode.

Other articles