How can I include a variable in a printf expression?
Here’s my example:
printf "%${cols}s", $_;
Where $cols is the number of columns
and $_ is a string.
The statement results in an “Invalid conversion” warning.
The problem ended up being that I forgot to chomp the variable. Gah. Thanks everyone.
I figured out your specific problem. Your code is correct. However, I suppose
$colsmight be a number read from user input, say like this:This works, and in numeric context
$colswill appear to be a number, but the problem is that$colsisn’t appearing in numeric context here. It’s in string context, which means that instead of expanding to"%5s", your format string expands to"%5\ns". The newline there is mucking up the format string.Change the code where you read
$colsto this:See the documentation on
chomp, as you may want to use it for other input reading as well.