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

Hi Monks, I am trying to format the record that i am writing out to the file. The length of the name is different for every record. In this case how can i position DOB at fixed position. basically i am trying to repeat the variable number of blanks between name and DOB to position DOB at the same location for every record. The code i have:

$name_length = length($std_name); $blank = " "; printf($std_name. "%$name_length $blank".$dob."%10c $blank".$age. "\n" +";

My output should be in the following format:


Name               DOB            AGE
Name111111         010190         30
Name222            020280         40

Thanks in advance.

Replies are listed 'Best First'.
Re: formating the record
by ikegami (Patriarch) on Oct 07, 2011 at 17:48 UTC
    printf("%-10s %-10s %s\n", $name, $dob, $age);
    printf("%-${max_name_length}s %-10s %s\n", $name, $dob, $age);
    printf("%-*s %-10s %s\n", $max_name_length, $name, $dob, $age);
Re: formatting the record
by roboticus (Chancellor) on Oct 07, 2011 at 18:22 UTC

    raj000:

    This is one of those times where you might want to break out the format statement (see perldoc format for details):

    #!/usr/bin/perl format STDOUT_TOP= Name DOB Age ---------------------- ------ --- . format STDOUT= @<<<<<<<<<<<<<<<<<<<<< @##### @## $name, $DOB, $age . while (<DATA>) { ($age, $DOB, $name) = split /,\s+/, $_; write; } __DATA__ 30, 010190, Name11111 40, 020280, Name222

    This gives me:

    $ perl 930233.pl Name DOB Age ---------------------- ------ --- Name11111 10190 30 Name222 20280 40 0 0

    (Which is why I should verify that I've parsed out enough fields, etc.) Anyway while some may dislike format, I find it useful for fixed-format file creation. You may also check out [doc://pack|pack if you don't care for format.

    Update: If you view the docs, you'll see how to get the leading zero put back on the numbers, how to center your text, have long strings wrap to the next line, and other interesting features.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: formating the record
by choroba (Cardinal) on Oct 07, 2011 at 20:29 UTC
Re: formating the record
by Not_a_Number (Prior) on Oct 07, 2011 at 18:56 UTC

    Hmm.. Consider:

    Valérie-Dominique von Wolfeschlegelsteinhausenbergerdorff

    You clearly need (as implied in ikegami's second solution above) to run an initial loop over your list of names to determine the length of your first output field.

    :)