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

I have a very simple perl script to convert a set of numbers into hex (converting dotted quad to hex). Here is the script:
#!/usr/bin/perl $octet1 = 10; $octet2 = 34; $octet3 = 2; $octet4 = 252; $hex1 = sprintf("%x", $octet1); $hex2 = sprintf("%x", $octet2); $hex3 = sprintf("%x", $octet3); $hex4 = sprintf("%x", $octet4); print "$hex1\n"; print "$hex2\n"; print "$hex3\n"; print "$hex4\n";
My output is this:
a 22 2 fc
How would you left justify/pad the values so that the desired output would be this?
0a 22 02 fc
This is an attempt to convert a dotted quad ip address from 10.34.2.252 to a hex value of 0a2202fc. If someone has a better suggestion on how to accomplish this, I'm all ears.

Replies are listed 'Best First'.
Re: left justify/pad hex value
by ikegami (Patriarch) on Mar 03, 2010 at 19:23 UTC

    Use %02x instead of %x

    If someone has a better suggestion on how to accomplish this

    unpack 'H*', pack 'C4', @octets;
      one other question. Let's say LIST.file contained:
      10.34.2.252 10.34.2.250 10.34.2.248
      I understand how to open the file. But I need a way to read each octet and place it accordingly into $octet1, etc.
        $ echo "10.34.2.252 > 10.34.2.250 > 10.34.2.248" | perl -e' use Socket; while ( <> ) { chomp; print "$_ -> ", unpack( "H*", inet_aton $_ ), "\n"; } ' 10.34.2.252 -> 0a2202fc 10.34.2.250 -> 0a2202fa 10.34.2.248 -> 0a2202f8
Re: left justify/pad hex value
by GrandFather (Saint) on Mar 03, 2010 at 20:08 UTC

    A major reason for using computers is to avoid doing the same thing over and over again. If you find yourself repeating essentially the same line of code multiple times then most likely there is a better way to do it. For the example to hand you could:

    use strict; use warnings; my @octets = (10, 34, 2, 252); printf "%02x\n", $_ for @octets;

    Prints:

    0a 22 02 fc

    True laziness is hard work