Luca,

I think you have a reasonable solution to the problem as you present it.
Adding a couple strategic comments might help the clarity.  A concern for
me is how the $condition variable gets set.

If the source data dictates the $condition then deriving them both in the
same parser might help:


    my ($condition, @fields) = parse_data($source_item);
    print sprintf $formats[ $condition ], @fields;

Or something.

if this works then $condition could be some string from the $source_item.
Then @formats could be %formats and $condition is the key and the printf
format is the value.  Here the key might serve as a bit of self
documentation given knowledge of the source data. Of course you are in a
better position to decide this than I am.

Also just a silly nit.  I tend to use the singular word rather than the
plural for array and hash names.  In the grand scope of things it's very
much a minor issue.

BTW you are right to avoid formats.

chris



On Tue, Jan 3, 2017 at 2:35 AM, Luca Ferrari <fluca1...@infinito.it> wrote:

> Hi all,
> I've a program that needs to print some fields formatted in different
> ways according to some conditions.
> The solution I come up is working, but I'm looking for a suggestion
> for something more elegant.
> What I do is something like the following:
>
> print sprintf $formats[ $condition ], @fields;
>
> where $condition is the condition used to select a sprintf format
> string out of an array (@formats) that contains something like:
>
> my @formats = (
>   qw( %09d %-1s %03d ... )
> , qw(%-4s %1s %09d %1s %-150s %-4s %011d)
> , ...
> );
>
> Now, while this approach is working really fine, it is a little hard
> to decode, especially considering that I've got some formats with 50+
> fields.
> I don't believe that using Perl formats is a solution, it will provide
> a quite longer configuration (consider I've got even fields specified
> as "-100%s"!).
> Any suggestion to get a more readable code?
>
> Thanks,
> Luca
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>
>

Reply via email to