Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Blankety-Blank Blanks and Zeros, etc.

by fizbin (Chaplain)
on Aug 26, 2005 at 18:44 UTC ( [id://486984]=note: print w/replies, xml ) Need Help??


in reply to Blankety-Blank Blanks and Zeros, etc.

This technique is adapted out of production C++ code that does something similar:

sub blank_formatter { my ($printf_format, $length) = @_; if (!defined($length)) { $printf_format =~ /^%(\d+)/ or die "Can't deduce length from $prin +tf_format"; $length = $1; } my ($blank) = ' ' x $length; sub { $_[0] ? sprintf($printf_format,$_[0]) : $blank; }; } sub my_printf { my ($format, @args) = @_; my (@printfargs) = (); while (@args) { my $arg = shift @args; if (ref($arg) and ref($arg) eq 'CODE') {push @printfargs, $arg->(s +hift @args);} else {push @printfargs, $arg;} } printf($format, @printfargs); } # similarly, if you need it, my_sprintf # Was: # printf( "A float: %12.4f$/", $root_beer ); my_printf( "A float: %s$/", blank_formatter('%12.4f'), $root_beer );

Then, if you need it, you can get whole aligned tables with something like:

my $fmt = blank_formatter('%12.4f'); my_printf("%10s: %s %s %s %s\n", $rowname, map {$fmt => $_} ($numcol1, $numcol2, $numcol3, $numcol4));

Similarly for other complicated formatting requirements. Just define your format generator so that it returns a sub reference that will take the thing to be formatted and returns a string, and then use printf as normal with %s placeholders.

-- @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://486984]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (None)
    As of 2024-04-19 00:12 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found