in reply to convert each character of a string to number

try:

#!/usr/bin/perl -l # http://perlmonks.org/?node_id=1181779 use strict; use warnings; sub convert { unpack('H*', shift() =~ tr/cd/qr/r) =~ tr/1267/0101/r; } for ( qw( abcd dcba abab cdcd abba caab ) ) { print "$_ -> ", convert($_); }

prints:

abcd -> 00011011 dcba -> 11100100 abab -> 00010001 cdcd -> 10111011 abba -> 00010100 caab -> 10000001

Replies are listed 'Best First'.
Re^2: convert each character of a string to number
by haukex (Archbishop) on Feb 12, 2017 at 09:45 UTC

    Hi tybalt89,

    Very clever :-)

    Building on your idea, this appears to be a bit faster: $string=~tr/abcd/\x00\x01\x10\x11/; unpack('H*', $string);

    Regards,
    -- Hauke D