Handle command line arguments with different sizes in Perl

When used in the literature in a Perl program, numbers are treated in the same way as in C: the prefix "0x" means hexadecimal, the prefix "0" means octal, and the prefix does not mean decimal:

$ perl -E 'print 0x23 . "\n"' 35 $ perl -E 'print 023 . "\n"' 19 $ perl -E 'print 23 . "\n"' 23 

I would like to pass Perl command line arguments using the same notation. for example, If I pass 23, I want to convert the string argument to a decimal value (23). If I pass 0x23, I want to convert to hexadecimal value (35), and 023 will be converted to octal (19). Is there a built-in way to handle this? I know hex () and oct (), but they interpret non-prefix numbers as hex / oct respectively (not decimal). Following this convention, it seems that I need the dec () function, but I do not think it exists.

+4
source share
1 answer

From http://answers.oreilly.com/topic/419-convert-binary-octal-and-hexidecimal-numbers-in-perl/ :

 print "Gimme an integer in decimal, binary, octal, or hex: "; $num = <STDIN>; chomp $num; exit unless defined $num; $num = oct($num) if $num =~ /^0/; # catches 077 0b10 0x20 printf "%d %#x %#o %#bn", ($num) x 4; 
+10
source

Source: https://habr.com/ru/post/1485111/


All Articles