I have a Perl code responsible for formatting output. Problem is I need to calculate correct number of tabs to be put before one particular character in each string (let’s say it’s /). So instead of getting lines with different lengths I’d like to get fixed-length strings (but as short as possible, using the longest as max). How should I approach this?
Example of output (with format commented out, just raw array):
Long title with some looong words / short text Another title / another short text
I need it like this:
title with some looong words / short text
Different title / another short text
This was my first attempt, but it didn’t involve using tabs after one particular character.
my $text = Text::Format->new;
$text->rightAlign(1);
$text->columns(65);
$text->tabstop(4);
$values[$i] = $text->format(@values[$i]);
There are two generally accepted ways to format text in Perl, so columns line up:
printfandsprintf. This is probably the most common way it’s done.I haven’t seen people use Perl Format specifications stuff in years. It was a big feature back in Perl 3.x heydays because Perl was mainly used as a super-awk replacement language(Practical Extraction and Reporting Language). However, the mechanism is still there, and I’m sure it’ll be fun to learn.
Now comes the second part of your query. You really don’t merely want the text to be formatted, you want it to be formatted with tabs.
Fortunately, Perl has a built in module called Text::Tabs. It’s one of those modules that does one or two obscure tasks, but does them well.
Actually,
Text::Tabsdoesn’t handle the two tasks it does well, but adequately.Produce your report using
sprintfor the build in Perl formatting capabilities. Save your whole report in an array. It has to be an array becauseText::Tabsdoesn’t handle NLs. Then use theunexpandfunction to replace spaces in that array into another array with tabs.WORD ‘O WARNING:
Text::Tabsdoes something very naughty: It imports the variable$tabstopinto your program without asking your permission. If you use a variable called$tabstop, you’ll have to change it. You can set$tabstopto be the number of spaces a tab represents. It’s set to 8 as a default.