Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Right justifying text in a template field

by olecs (Scribe)
on Dec 14, 2005 at 13:51 UTC ( [id://516643]=perlquestion: print w/replies, xml ) Need Help??

olecs has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,
say I have the following template and code - (note that the code is just for illustration, it might not run):
$TEMP = "\@0 A1 \@1 A12"; $string = "AAAA"; $res = pack($TEMP, "V", $string); print "$res\n";
Now, when printing $res AAAA will be left justified and followed by 8 blanks - is it possible to make it right justified using the template mechanism? I could of course resort to using printf instead, but for my current purpose templates feel so right

rgds,
Ole C.

Update
As ikegami suggested I will use sprintf inside the pack statement to format the text the way it needs to be, something like:
pack($TEMP, "V", sprintf("%12s", "$string"));

takes care of it. The reason for using pack in the first place is that I have to create very long lines with different data and a very rigid structure for where the data should be. pack makes it easy to ensure that everything comes in the right place.

Replies are listed 'Best First'.
Re: Right justifying text in a template field
by ikegami (Patriarch) on Dec 14, 2005 at 14:46 UTC

    pack is meant for creating C structs, not for formatting. Try printf/sprintf:

    $formatted = sprintf('%5s', 'abc'); # ' abc' $formatted = sprintf('%-5s', 'abc'); # 'abc '

    You could always pack what sprintf returns, if you need pack.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://516643]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-25 07:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found