perl - using printf to create columnar data -


i new perl , scripting in general. have 5 variables hold data , need print them 5 columns next each other. here code have now.

$i = 0; foreach $line (<inf>){     chomp $line;     @line=split / +/, $line;     $i = $i + 1;     if ($i > $n+1) {         $i = 1;         $numdata = $numdata + 1;     }     if ($i == 1) {         printf "%20s\n", $n, "\n";     } else {         print  $i-1, "bead", $line[$col], $line[$col+1], $line[$col+2], "\n";     }     # other statistics } 

the output looks like:

                   5 1bead0.00000e+000.00000e+000.00000e+00 2bead0.00000e+000.00000e+000.00000e+00 3bead0.00000e+000.00000e+000.00000e+00 4bead0.00000e+000.00000e+000.00000e+00 5bead0.00000e+000.00000e+000.00000e+00                    5 1bead9.40631e-02-3.53254e-022.09369e-01 2bead-6.69662e-03-3.13492e-012.62915e-01 3bead2.98822e-024.60254e-023.61680e-01 4bead-1.45631e-013.45979e-021.50167e-01 5bead-5.57204e-02-1.51673e-012.95947e-01                    5 1bead8.14225e-028.10216e-022.76423e-01 2bead2.36992e-02-2.74023e-014.47334e-01 3bead1.23492e-011.12571e-012.59486e-01 4bead-2.05375e-011.25304e-011.85252e-01 5bead5.54441e-02-1.30280e-015.82256e-01 

i have tried using "%6d %9d %15.6f %28.6f %39.6f\n" before variables in print statement try space data out; however, did not give me columns hoped for. help/ suggestions appreciated.

if you're using perl , doing more complex stuff, may want perlform, designed kind of thing, or module text::table.

as using printf though, can use padding specifiers consistent spacing. instance, using perl docs on it, make sure field width before .: printf string should more (check out "precision, or maximum width" section):

printf "%6.d %9.d %15.6f %28.6f %39.6f" 

also, if things in array, can pass array second argument printf , save typing out. i've prepended 2 other items example unshift:

unshift(@line, $i-1, "bead"); printf "%6.d %10s %15.6f %28.6f %39.6f\n", $line; 

note %s placeholders don't have . precision specifier, leave out that. if want e-notation numbers, use %e or %g instead of %f (%39.6e).

also, perl questions, check out perl monks - of answer culled a question there.

p.s. given 1 of example columns, here's proof-of-concept script tried make sure worked:

perl -e '@line = (8.14225e-02,8.10216e-02,2.76423e-01);     unshift(@line, 4, "bead");     printf "%6.d %10s %15.6f %28.6f %39.6e\n", @line;' 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -