Perl : Regular Expression with changing decimal to hexadecimal

Viewed 146

I have file in which many decimal number are given in form like

Hello
Hey
'37888' =>'A'
'37890' =>'B'
'37642' =>'C'

Now I have tried this,

while (my $line = <$Log1>) {
    $line =~ s/'(\d+)'/(\hex(\d+))/g);    #Here I am getting error
    print $line;
    };
sub hex{
my $num = @_;
my $n= ("0x"."%x\n", $num);
return $n; 
};   

I thought (\hex(\d+)) will work. Any suggestion how to do it?

2 Answers

You can use sprintf to format a decimal number as hexadecimal and use s/// with e to evaluate sprintf:

use warnings;
use strict;

while (my $line = <DATA>) {
    $line =~ s/(\d+)/sprintf '0x%x', $1/eg;
    print $line;
}

__DATA__
Hello
Hey
'37888' =>'A'
'37890' =>'B'
'37642' =>'C'

Output:

Hello
Hey
'0x9400' =>'A'
'0x9402' =>'B'
'0x930a' =>'C'

Also, there is already a builtin hex function, which means you should avoid creating your own function named hex.

Perl's hex goes the other way. It interprets a string as if it's already the hexadecimal representation of a number.

I have some shell aliases for quick conversions:

$ grep alias ~/.bash_profile | grep 2[hdob]
alias d2h="perl -e 'printf qq|%X\n|, int( shift )'"
alias d2o="perl -e 'printf qq|%o\n|, int( shift )'"
alias d2b="perl -e 'printf qq|%b\n|, int( shift )'"
alias h2d="perl -e 'printf qq|%d\n|, hex( shift )'"
alias h2o="perl -e 'printf qq|%o\n|, hex( shift )'"
alias h2b="perl -e 'printf qq|%b\n|, hex( shift )'"
alias o2h="perl -e 'printf qq|%X\n|, oct( shift )'"
alias o2d="perl -e 'printf qq|%d\n|, oct( shift )'"
alias o2b="perl -e 'printf qq|%b\n|, oct( shift )'"
alias b2h="perl -e 'printf qq|%X\n|, oct( q(0b) . shift )'"
alias b2o="perl -e 'printf qq|%o\n|, oct( q(0b) . shift )'"
alias b2d="perl -e 'printf qq|%d\n|, oct( q(0b) . shift )'"
Related