Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Table or structured output to stdout

Status
Not open for further replies.

jerehart

Programmer
Joined
Jun 10, 1999
Messages
61
Location
US
Hey I want to output some text from a script where everything lines up regardless of the output string size. I am looking for something like a setw(#spaces) type thing. any ideas?
 
You can use printf formatting, perl's format statements for reporting, or you can pad your strings. Here's a handy couple of routines for left and right padding strings:
Code:
#---------------------------------------------------------------------
# LPad
#---------------------------------------------------------------------
# Pads a string on the left end to a specified length with a specified
# character and returns the result.  Default pad char is space.
#---------------------------------------------------------------------

sub LPad {

local($str, $len, $chr) = @_;

$chr = " " unless (defined($chr));
	
return substr(($chr x $len) . $str, -1 * $len, $len);

} # LPad

#---------------------------------------------------------------------
# RPad
#---------------------------------------------------------------------
# Pads a string on the right end to a specified length with a specified
# character and returns the result.  Default pad char is space.
#---------------------------------------------------------------------

sub RPad {

local($str, $len, $chr) = @_;

$chr = " " unless (defined($chr));
	
return substr($str . ($chr x $len), 0, $len);

} # RPad
#---------------------------------------------------------------------

Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top