in reply to Converting quoted strings to numbers in array

For Perl, strings and numbers are different, even if it's easy to convert between them. A string can be specified in quotes, e.g.
'string' "another string" q(yet another) qq<or like this>

etc. Numbers can be specified in different ways, too:

12 1_2 0b1100 0x0c

All of them are just different ways how to represent the number 12. The problem is that 0x0c as a string , i.e. in quotes, is not interpreted as a number, but as a string. To convert it to a number, you need to use the oct function:

#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my @arr = qw( 10 10 20 0x47 1 30 45 45 ); my @converted = map /^0x/ && oct || $_, @arr; say for @converted;

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: Converting quoted strings to numbers in array
by pritesh_ugrankar (Monk) on Apr 23, 2017 at 20:59 UTC

    Hi Choroba,

    Thank you for replying. Please let me know if there is a reason to use a oct function for a hex string?

    Thinkpad T430 with Ubuntu 16.04.2 running perl 5.24.1 thanks to plenv!!

      If you were dealing with a mixture of binary (as 0b...), hexadecimal (as 0x...), and octal strings, e.g. in a loop, then oct would be useful.

      When you know it's a hexadecimal string (e.g. /^0x/ && ...), I'd use the hex function. It makes your intent clear and obvious and, in my opinion, the code is far more readable.

      The actual result is the same whichever you use:

      $ perl -E 'say oct "0x47"; say hex "0x47"' 71 71

      And just a word of warning, /^0x/ may not do what you want:

      $ perl -E 'say "0x47_not_hex" =~ /^0x/ ? "is hex" : "is NOT hex"' is hex $ perl -E 'say "0x47_not_hex" =~ /^0x[0-9a-fA-F]+$/ ? "is hex" : "is N +OT hex"' is NOT hex

      — Ken

      The word oct in my reply was a link. Have you clicked it and read the documentation?

      > If EXPR happens to start off with 0x , interprets it as a hex string.

      Maybe not the best name for such a function, but that's how it is.

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,