mfawbush has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I've been beating on this for a while now that I'm just plumb confused now. I'm sure it's so simple and it's right in front of me. Need to send a five byte block to serial port. The snippet of code below works, however I need to replace all the values behind the hex escape "\x" with what the user puts in from STDIN strings. I've tried pack and hex with no success. Thank you in advance for your help.

#Works $port->write("\x01\x42\x62\x00\x01");

Replies are listed 'Best First'.
Re: hex escape Question
by choroba (Cardinal) on Jul 28, 2015 at 17:39 UTC
    It's not clear what the user inputs. The following code handles the strings 01, 42, etc.:
    print map chr hex, qw( 01 42 62 00 01 );

    Update: To use pack, you can

    print map { pack 'H2', $_ } qw( 01 42 62 00 01 );

    or

    print pack 'H*', '0142620001';
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      another variation:
      my @array = qw(01 42 62 00 01); print pack 'H2' x @array, @array;

        I was trying to capture it something like this:

        my $sfreq=<STDIN>; #014.262.00 my ($Mhz,$Khz,$hz)=split(/\./,$sfreq); my $h1=substr($Mhz,0,2); #h1=pack('H*',$h1); my $h2=substr($Mhz,2,1).substr($Khz,0,1); #$h2=pack('H*',$h2); my $h3=substr($Khz,1,2); #$h3=pack('H*',$h3); my $h4=substr($hz,0,2); my $hfreq="$h1$h2$h3$h4";