Elegance and wit are in the mind of the beholder - my favorite solutions are the ones that work and work reliably. In any case, since you have synchronized arrays, you have a couple of options for how to traverse them - e.g. you can either use an index variable as you have done or you can use
shift to destructively-traverse one or more of the arrays, as I have done below. As well, rather than the branching you have done, I took advantage of the fact that
printf silently drops unused terms to move the conditional into the format statement. I have also abstracted the field-size and precision to variables at the top of the script to aid in future-proofing.
#!/usr/bin/perl
use strict;
use warnings;
my $best = {1 =>[1,2]};
my $kept_best = {1 =>[1]};
my $width = 10;
my $precision = 5;
printf "%-${width}s %-${width}s\n", "BEST", "SELECTED BEST";
foreach my $value (sort keys %$best){
foreach my $bind_energy (@{$best->{$value}}){
my $kept = shift @{$kept_best->{$value}};
my $format = "\%${width}.${precision}f";
$format .= defined $kept ? " $format\n" : "\n";
printf $format, $bind_energy, $kept;
}
}
If you find the variable $format approach unclear, you can achieve the same result by just using multiple printfs and an if conditional:
#!/usr/bin/perl
use strict;
use warnings;
my $best = {1 =>[1,2]};
my $kept_best = {1 =>[1]};
my $width = 10;
my $precision = 5;
my $format = "\%${width}.${precision}f ";
printf "%-${width}s %-${width}s\n", "BEST", "SELECTED BEST";
foreach my $value (sort keys %$best){
foreach my $bind_energy (@{$best->{$value}}){
printf $format, $bind_energy;
my $kept = shift @{$kept_best->{$value}};
printf $format, $kept if defined $kept;
print "\n";
}
}
TIMTOWTDI.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.