How to visualize undefined values ​​from printf in Perl?

I am looking for an elegant way to indicate undefined values ​​in situations where normally formatted numbers are displayed. I will come up with a small example. For starters, you certainly cannot use this:

#!/usr/bin/perl use strict; use warnings; for my $s (1, 1.2, undef, 1.3) { printf "%5.2f\n", $s; } 

... because "using warnings" leads you to "Using uninitialized value ..." in the third iteration. So, the next step is something like this:

 #!/usr/bin/perl use strict; use warnings; for my $s (1, 1.2, undef, 1.3) { printf "%5.2f\n", $s//0; } 

And, boy, I like the new 5.10 '//' statement, by the way. But this is really not what I want, either because the value of $ s is not zero, but undefined. I really want something like this:

 #!/usr/bin/perl use strict; use warnings; for my $s (1, 1.2, undef, 1.3) { printf "%5.2f\n", $s//q(); } 

... but I can’t because it causes the problem "Argument" "not numeric ..." on the third value.

This brings me to the threshold of my question. I can, of course, write code that checks every number that I emit for definiteness, and creates a whole different line of printf format other than% f, but, well, ... yuck.

Has anyone identified a good way to handle this type of requirement?

+4
source share
3 answers

I don’t think there is anything there - this is exactly what you want to do.

 use strict; use warnings; my($raw) = [1, 1.2, undef, 1.3]; my($formatted) = [map((defined $_ ? sprintf('%5.2f', $_) : "(undef)"), @$raw)]; print '$formatted: <', join('> <', @{$formatted}), qq(>\n); 
+3
source

It is not very, but I just do it like

 defined($s) ? printf "%f.2f\n", $s : print "undef\n"; 
+3
source

I think the nice way is to write / get a generic simplex that takes whatever you throw at it, and then:

 #!/usr/bin/perl use strict; use warnings; use MyPrettyPrinter; for my $s (1, 1.2, undef, 1.3) { print MyPrettyPrinted($s), "\n"; } 
+3
source

All Articles