Some parts of this page were machine translated.
Powered by Yandex.Translate
http://translate.yandex.com/
In the Perl programming language has a built-in function hex()
.
hex()
in Perl
In the Perl programming language has a built-in function hex()
.
Function hex()
converts a number from hexadecimal format to decimal.
Here's an example:
#!/usr/bin/perl
print hex('0xFF');
The program will display 255
.
If the function hex
not given no arguments, the function works with default variable $_
:
#!/usr/bin/perl
$_ = '0x100';
print hex(); # 256
In that case if the variable $_
is undef
and used use warnings;
, will warning:
#!/usr/bin/perl
use strict;
use warnings;
my $dec = hex();
Use of uninitialized value $_ in hex at script.pl line 6.
Standard using hex()
is to pass it a single argument.
If the transfer function hex()
more than one argument, it will be an error and code execution will be stopped.
Too many arguments for hex at script.pl line 3, near "2)"
Execution of script.pl aborted due to compilation errors.
If you need to convert multiple values, you can use map
:
#!/usr/bin/perl
use Data::Dumper;
my @hex = ('0xA', '0xB', '0x11');
my @dec = map { hex } @hex;
warn Dumper \@dec;
The string can begin with 0x
, but not necessarily. Case-sensitive values are not
has.
Here are a few examples. In this example, all the call to the function hex()
return
the same value of the — number 2748.
#!/usr/bin/perl
use strict;
use warnings;
use feature qw(say);
say hex('0xABC');
say hex('0XABC');
say hex('0xabc');
say hex('XABC');
say hex('xABC');
say hex('abc');
say hex('AbC');
A function can not work with fractional hexadecimal numbers. When you try to convert such the number of the warning:
#!/usr/bin/perl
use strict;
use warnings;
print hex('0x10.8');
Illegal hexadecimal digit '.' ignored at script.pl line 6.
16
Function hex()
always returns a number.
Here is the output of the command perldoc -f hex
:
hex EXPR
hex Interprets EXPR as a hex string and returns the corresponding
numeric value. If EXPR is omitted, uses $_.
print hex '0xAf'; # prints '175'
print hex 'aF'; # same
$valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/
A hex string consists of hex digits and an optional "0x" or "x"
prefix. Each hex digit may be preceded by a single underscore,
which will be ignored. Any other character triggers a warning
and causes the rest of the string to be ignored (even leading
whitespace, unlike "oct"). Only integers can be represented, and
integer overflow triggers a warning.
To convert strings that might start with any of 0, "0x", or
"0b", see "oct". To present something as hex, look into
"printf", "sprintf", and "unpack".