http://www.perlmonks.org?node_id=1024812

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

I'm trying to use perl's printf function to get my output formatted correctly, but I'm having some trouble. Below is my practice printf.
printf ("'%-5'\n", 1234567);

It's giving me an invalid conversion error.

What would be the correct printf statement to line up output that will look like this.

ID IP PORT 1 192.168.1.1 10001 2 192.168.1.2 10001 3 192.168.1.3 10001 10 192.168.1.10 10001 150 192.168.1.150 10001

My output needs to line up even when the ID digits become double and triple digits (ie 10, 100). Using print, it moves everything over one space when the number of digits in ID increases. I've been reading about printf documentation but apparently I don't understand it. I also am unsure of how to output IP address with printf (floating points with multiple decimals). I'm more used to C++ <iomanip> header where you can just say setw(5) and left and you're done. Any help would be appreciated.

Replies are listed 'Best First'.
Re: Help formatting with printf
by McA (Priest) on Mar 21, 2013 at 19:46 UTC
    printf("%-5s %-15s %-5s\n", $id, $ip, $port);

    McA

      Well, that was ridiculously simple. I feel stupid. Thanks for the help, it works perfectly.