I'm printing some data,
printf( "A float: %12.4f$/", $root_beer );
and, later, some moron, usually me, decides that if $root_beer is zero and/or an empty string the printed field should maintain its width but be blank.

A common place issue and my reflex is to do the same things I did in C decades ago: Use a variable as a conversion specifier ($fmt="%12s") or use sprintf then printf.

I am asking for people's best practices on printing blank fields for values like zero, undef and empty string in places where the conversion specifier would expect a numeric and other like issues.

Update: The nature of the replies I've gotten aren't what I hoped for. As a programming problem I'd like to hear the voice of experience. But I'd also like to hear about the quirks (impedance mismatch) of what people want to read in their reports versus what is trivial to output. ( Re-Update: Much later and I've found fizbin's code useful.)

My best solution to date:

my $fmt = fmt_num_or_blank( $width, $data); printf( "A float: $fmt$/", $root_beer );
Which is least invasive of the printf.

My best conception is something like:

# Mnemonic: N nothing for nought nor null printf( "A float: %N12.4f$/", $root_beer );
but at best I could only weakly implement that.

Over the years there has been a lot of hate mail for printf formatting as being messy and error prone. I think it just reflects the problem domain. Are there other output massagers to look at?

Be well,
rir


In reply to Blankety-Blank Blanks and Zeros, etc. by rir

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.