Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: I don't use printf enough

by demerphq (Chancellor)
on Oct 22, 2003 at 23:12 UTC ( #301419=note: print w/ replies, xml ) Need Help??


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



Comment on Re: I don't use printf enough
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (12)
As of 2014-11-24 16:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (143 votes), past polls