crdrtl has asked for the wisdom of the Perl Monks concerning the following question:

Here's my code:

#!/usr/bin/perl
use strict;

my @stuff;
push @stuff, "%Utilization";
my $format= "%-13s ";
my $ostr;
$format .= "\n";
$ostr = sprintf("$format", @stuff);
printf $ostr;
$ostr = sprintf "$format", $stuff[0];
print $ostr;
$ostr = sprintf "$format", "%Utilization";
print $ostr;

Here's the output:

0tilization
%Utilization
%Utilization


Note that if I use an array containing an element that has a % sign (no adjacent %s), it gets interpreted - seemingly as if it were part of the format.

Any ideas why? Is there a trick to get around this easily?

I did notice that if I make the string in the array to display "%%Utilization", it prints "%Utilization".

Replies are listed 'Best First'.
Re: formating string var with % in it
by Corion (Patriarch) on Sep 22, 2010 at 17:46 UTC
    $ostr = sprintf("$format", @stuff); printf $ostr;

    That second printf is trying to do another interpolation. You want to use print here. Had you used warnings or if you ran your program using perl -w, Perl would raised at least a warning for the printf, even if that warning is misleading (in 5.10, fixed in 5.12 or at least 5.13.5):

    > perl -wle "$f=sprintf'%-13s','%util';print $f;printf $f" Use of uninitialized value $f in printf at -e line 1. 0til

    Of course, $f is not uninitialized, but there is no named variable anyway.

      Holy crap. Definitely been staring at the code too long - didn't notice it until you said "That second printf". I'm like - what second printf ... D'OH! Thank you. I'm humbled.
Re: formating string var with % in it
by kennethk (Abbot) on Sep 22, 2010 at 17:48 UTC
    If I swap line 10 from printf to print, I get the result:

    %Utilization %Utilization %Utilization

    which is what I assume you meant. You would have gotten a hint (Use of uninitialized value in printf...) if you used warnings as well as strict - see Use strict warnings and diagnostics or die.

    Rather than formatting with <br> and entities, good form says you should wrap code in <code> tags. Not only will it make sure you didn't miss an escape, it will provide a convenient download link. See Writeup Formatting Tips.