开发者

How to increment hex in perl

CODE

use warnings;
use strict;

my $mv = 41;
my $tmp =1;
while($tmp<26)
{
print  chr (hex($mv++));开发者_如何学JAVA
print "\n";
$tmp++;
}

OUTPUT ABCDEFGHIPQRSTUVWXY`abcde

Code generate English character set

Issue

Few characters are missing "J->O && Z "

Reason J hex value is 4a

How to increment the hex value in perl or any another way to generate the character set?


According to a comment you left, your end goal appears to be to produce the mapping A=1,B=2. Here's code to achieve that:

my @symbols = 'A'..'Z';
my %map = map { $symbols[$_] => $_+1 } 0..$#symbols;

Or (less flexible):

my %map = map { $_ => ord($_)-ord('A')+1 } 'A'..'Z';


You may want

for my $i (65..122) {
    print chr($i);
}

Also you may like

for my $char ("a".."z", "A".."Z") {
    print $char;
}


Setting aside your actual stated goal (the mapping of characters to codes), the problem here is that $mv is not a hexadecimal value, it's a decimal value that you stringify and treat as hexadecimal. That means that the next value after 49 is 50, not 4a. If $mv were in hex from the outset, you wouldn't have this problem (and you wouldn't need the call to hex(), either). If you declare $mv as so:

$mv = 0x41;

then you will find that the value 49 is correctly followed by 4a. Using your code example:

my $mv = 0x41;
my $tmp = 1;
while ($tmp < 26)
{
    print chr($mv++);
    print "\n";
    $tmp++;
}

You should get the original intended results.


Try something like

print chr for (65..90);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜