http://www.perlmonks.org?node_id=301419


in reply to I don't use printf enough

I find that I often end up converting simple concatenation or interpolating print statements into (s)printfs. Especially as they get larger and more cumbersome I find the template-arg list approach more convenient and easier to manage. A useful trick is things like this:

printf "Some string %s in the file %s for %s", map { defined $_ ? $_ : 'undef' } $arg1,$arg2,$arg3;

Or if you are using ternaries in the output or whatever. Unlike BrowserUK and others I find printf a lot easier to manage. Also heres a cute trick (that I will eventually release as a CPAN module with more features)

package _XSprintf; use overload '""' => sub { shift->() }; package main; sub xsprintf { my $fmt =shift; my $bind=\@_; return bless sub { sprintf $fmt,@_ ? @_ : @$bind },'_XSprintf'; } my ($char,$ord,$bits)=('A'); my $diag=xsprintf("%s : %3d => '%8s'\n",$char,$ord,$bits); for ($char='A';length($char)==1;$char++) { $ord=ord $char; $bits=unpack 'B*',$char; print $diag; } __END__ A : 65 => '01000001' B : 66 => '01000010' C : 67 => '01000011' D : 68 => '01000100' E : 69 => '01000101' ...

Possibly not the most persuasive example, but on a number of occasions ive used this to greatly simplify diagnostics output inside of loops. Unfortunately it doesnt play nicely with for(LIST) because the iterator var is aliased, and accordingly it isn't in the bound argument array.


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi