Some parts of this page were machine translated.
Powered by Yandex.Translate
http://translate.yandex.com/
Dans le langage de programmation Perl, il ya une fonction intégrée hex()
.
hex()
en Perl
Dans le langage de programmation Perl, il ya une fonction intégrée hex()
.
La fonction de hex()
convertit un nombre de format hexadécimal en décimal.
Voici un exemple:
#!/usr/bin/perl
print hex('0xFF');
Le programme affichera 255
.
Dans ce cas, si la fonction hex
n'est pas transmises à aucun argument, la fonction travaille avec дефолтной variable $_
:
#!/usr/bin/perl
$_ = '0x100';
print hex(); # 256
Dans ce cas si la variable $_
est undef
et utilisé use warnings;
, ce sera un avertissement:
#!/usr/bin/perl
use strict;
use warnings;
my $dec = hex();
Use of uninitialized value $_ in hex at script.pl line 6.
L'utilisation standard de la fonction hex()
— c'est de lui transmettre un argument.
Si vous passez de la fonction hex()
a plus d'un argument, ce serait une erreur et l'exécution de code sera arrêté.
Too many arguments for hex at script.pl line 3, near "2)"
Execution of script.pl aborted due to compilation errors.
Si vous voulez convertir plusieurs valeurs, vous pouvez utiliser map
:
#!/usr/bin/perl
use Data::Dumper;
my @hex = ('0xA', '0xB', '0x11');
my @dec = map { hex } @hex;
warn Dumper \@dec;
La chaîne peut commencer avec 0x
, mais il n'est pas obligatoire. La casse des caractères de la valeur n'est pas
a.
Voici quelques exemples. Dans cette exemple, tous les appels à la fonction hex()
renvoient
la même valeur — nombre de 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');
La fonction n'est pas capable de travailler avec des fractions en nombres hexadécimaux. Lorsque vous tentez de convertir un tel nombre d'avertissement:
#!/usr/bin/perl
use strict;
use warnings;
print hex('0x10.8');
Illegal hexadecimal digit '.' ignored at script.pl line 6.
16
La fonction hex()
renvoie toujours un nombre.
Voici la sortie de la commande 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".