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

I have an variable which has an value like 12345678, Want to change the value to 12 34 56 78. Below is an code which does that, but it is also inserting an space at the end. Does any one known what's wrong???
while ($i < 4) { $ID1=`printf "%024x", $i`; printf "Value of ID1 = $ID1\n"; $ID1 = join ' ', unpack("(A2)*",$ID1); print "After join command:$ID1\n"; $i++; } bash-3.00# ./genID.pl Value of ID1 = 000000000000000000000000, After join command:00 00 00 00 00 00 00 00 00 00 00 00 , Value of ID1 = 000000000000000000000001, After join command:00 00 00 00 00 00 00 00 00 00 00 01 , Value of ID1 = 000000000000000000000002, After join command:00 00 00 00 00 00 00 00 00 00 00 02 , Value of ID1 = 000000000000000000000003, After join command:00 00 00 00 00 00 00 00 00 00 00 03 ,

Replies are listed 'Best First'.
Re: perl Question
by ikegami (Patriarch) on Feb 22, 2008 at 21:52 UTC
    It's cause $ID1 is "12345678," rather than "12345678". Get rid of the comma in the printf line. You might have to chomp($ID1); too.

    Is $ID1 = `printf ...`; just an example? It would be much better to do $ID1 = sprintf "%024x", $i;.

Re: perl Question
by FunkyMonk (Bishop) on Feb 22, 2008 at 21:59 UTC
    Why use the external command printf when you can use the sprintf builtin?
    while ($i < 4) { $ID1=sprintf "%024x", $i; printf "Value of ID1 = $ID1\n"; $ID1 = join ' ', unpack("(A2)*",$ID1); print "After join command:$ID1\n"; $i++; }

Re: perl Question
by chromatic (Archbishop) on Feb 22, 2008 at 22:06 UTC

    The problem isn't the space. The problem is that the results of the printf program add a comma to the end of your variable.

    Use the sprintf builtin instead:

        my $ID1 = sprintf "%024x", $i;