in reply to conditional string formatting

Simple and maintainable:
my %formats = ( 1 => ' %s ', 2 => ' %s ', 3 => ' %s', 4 => '%s', ); for my $x ("a", "bb", "ccc", "dddd") { printf $formats{length($x)}, $x; print "\n"; } ###################### a bb ccc dddd

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^2: conditional string formatting
by AnomalousMonk (Archbishop) on Jun 10, 2015 at 00:34 UTC

    ++Very nice, and very easily extended to handle a default case!

    c:\@Work\Perl\monks>perl -wMstrict -le "my %formats = ( 1 => ' %s ', 2 => ' %s ', 3 => ' %s', 4 => '%s', +); ;; for my $x ('a', 'bc', 'def', 'ghij', 'klmno') { printf qq{'@{[ $formats{length($x)} // '%4.4s' ]}' \n}, $x; } " ' a ' ' bc ' ' def' 'ghij' 'klmn'


    Give a man a fish:  <%-(-(-(-<

      ...easily extended to handle a default case!
      Yes, I forgot to handle that. The defined-or touch is nice.

      While the @{[]} wrapper does the job, is it completely necessary? (Perhaps I have missed something in my uncaffeinated state?) Other than a quick crutch for interpolating inside qq{} while adding single quotes and appending a newline?

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

        Not necessary, just a quick, easy path to some example code.


        Give a man a fish:  <%-(-(-(-<