in reply to Print multiple hashes of arrays at same time

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.

Replies are listed 'Best First'.
Re^2: Print multiple hashes of arrays at same time
by tomdbs98 (Beadle) on Jul 19, 2010 at 19:04 UTC
    It took me a few minutes to understand your use of format in the first example, but I love it, very clever.