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

Dear Wise Monks,

I have fixed-width data file where numbers are padded on the left. I want to be able to use unpack to extract these number, but unpack wants the data to the right-padded. What can I do?

print '>' . unpack('A6','123 ') . "<\n"; # prints >123< print '>' . unpack('A6',' 123') . "<\n"; # prints > 123< <---- extra leading space??

Replies are listed 'Best First'.
Re: pack/unpack left padding
by moritz (Cardinal) on Sep 10, 2007 at 18:52 UTC
    unpack does what the documentation says it does: it extracts six characters into a string.

    If you want to get rid of the whitespace padding, you can just use it in numerical context:

    $ perl -wle 'print ">", 0+" 123";' >123

    Note that a blank is nothing special to unpack.

Re: pack/unpack left padding
by ikegami (Patriarch) on Sep 10, 2007 at 19:13 UTC

    0+$n works great for numbers, as mentioned already. Here's a more general solution:

    $n =~ s/^\s+//;
Re: pack/unpack left padding
by Skeeve (Parson) on Sep 10, 2007 at 18:52 UTC
    how about (unpack('A6','   123')+0)

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e