功能 oct() Perl

在Perl编程语言都有一个内置的功能 oct().

功能 oct() 转换为数量从八号系统,以小数。 但是,即使这种功能可以转换的一些中小数系统 从二和十六.

这里有一个例子:

▶ Run
#!/usr/bin/perl

use feature qw(say);

say oct('10'); # 8
say oct('0x10'); # 16
say oct('0b10'); # 2

参数

如果功能 oct 不会给没有参数、功能适用 的默认可变 $_:

▶ Run
#!/usr/bin/perl

$_ = 123;

print oct(); # 83

在这种情况下,如果可变 $_undef 和使用 use warnings;,会警告:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;

my $dec = oct();
Use of uninitialized value $_ in oct at script.pl line 6.

标准的使用 oct() 是通过一个单一的论点。

如果传输功能 oct() 多个参数,它将是一个错误和执行代码将被停止。

Too many arguments for oct at script.pl line 3, near "2)"
Execution of script.pl aborted due to compilation errors.

如果需要转换的多重价值观,可以使用 map:

▶ Run
#!/usr/bin/perl

use Data::Dumper;

my @oct = (100, 200, 300);

my @dec = map { oct } @oct;

warn Dumper \@dec;

如果功能是通过一串的开始 0x0X、功能 oct() 解释这串数字十六符号和返回 这个数字是十进制。

但如果串的开始 0bOB,然后 ord() 考虑线数量 在binary notation和返回其小数表示。

如果在 oct() 票数,其中有一个角色,是不是 包括在范围内的数字从 07,然后 oct() 将返回 0,但也包括在内 use warnings; 会警告:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;
use feature qw(say);

say oct(90210);
Illegal octal digit '9' ignored at script.pl line 7.
0

功能 oct() 不能工作的小数值:

▶ Run
#!/usr/bin/perl

use strict;
use warnings;
use feature qw(say);

say oct('10.7');
say oct('0X10.F');
say oct('0B10.11');
8
16
2
Illegal hexadecimal digit '.' ignored at script.pl line 8.
Illegal binary digit '.' ignored at script.pl line 9.

回值

功能 oct() 总是返回的数量。

官方文件

这里是输出的命令 perldoc -f oct:

    oct EXPR
    oct     Interprets EXPR as an octal string and returns the corresponding
            value. (If EXPR happens to start off with "0x", interprets it as
            a hex string. If EXPR starts off with "0b", it is interpreted as
            a binary string. Leading whitespace is ignored in all three
            cases.) The following will handle decimal, binary, octal, and
            hex in standard Perl notation:

                $val = oct($val) if $val =~ /^0/;

            If EXPR is omitted, uses $_. To go the other way (produce a
            number in octal), use "sprintf" or "printf":

                my $dec_perms = (stat("filename"))[2] & 07777;
                my $oct_perm_str = sprintf "%o", $perms;

            The "oct" function is commonly used when a string such as 644
            needs to be converted into a file mode, for example. Although
            Perl automatically converts strings into numbers as needed, this
            automatic conversion assumes base 10.

            Leading white space is ignored without warning, as too are any
            trailing non-digits, such as a decimal point ("oct" only handles
            non-negative integers, not negative integers or floating point).

相关的主题

其他文章