How to perform dynamic formatting with perl during write?
I have a format which is defined like below:
format STDOUT =
------------------------------------
|Field1 | Field2 | Field3 |
------------------------------------
|@<<<<<<<<<<| @<<<<<<<<<<<| @<<<<< |~~
shift(@list1),shift(@list2),shift(@list3)
------------------------------------
.
write STDOUT;
So the questions are as below:
- Is it possible to make the list of values printed dynamic? e.g. If list 1 contains 12 elements, and if $flag1 is defi开发者_如何学Pythonned, then print only elements 0..10 instead of all 12. I tried doing this by passing $flag as a parameter to the sub which generates the report. However, the last defined FORMAT seems to always take precedence and the final write when it happens, applies the last format no matter what the condition is.
- Is it possible to also add/hide fields using the same process. e.g. If $flag2 is defined, then add an additional field Field4 to the list?
I don't think format feature is very suitable for dynamic approach -- you can try to use sprintf
or pack
templates. Their formats are simple strings that are easier to build on the fly.
To me it seems like you are doing to much at once.
Before you format your output, create a check for the flag, then create a scalar based on the flag (e.g. the first 10 elements of the array). Then put the string in the output.
You could also make a scalar which is the WHOLE table+entry of Field4, then if flag two is set, in an if statement, concatenate the scalar to your output.
It is better to take many steps to do the job correctly, than trying to be "clever" and do all the steps in few lines of code.
By hacking at the internals essentially, man perlform Accessing Formatting Internals
use Carp;
sub swrite {
croak "usage: swrite PICTURE ARGS" unless @_;
my $format = shift;
$^A = "";
formline($format,@_);
return $^A;
}
$string = swrite(<<'END', 1, 2, 3);
Check me out
@<<< @||| @>>>
END
print $string;
精彩评论