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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pad a String 2

Status
Not open for further replies.

rhnewfie

Programmer
Jun 14, 2001
267
CA
Is there a simple function that will pad a string to a certian length with a certian character. Say I had a string of length 4 that I wanted padded to 20 using 16 spaces.

Thanks

RHNewfie There are 3 Types of People in the World
Those Born to Think Logically
Those that can Learn to Think Logically
Those that Shouldn't Try
 
You didn't specify right or left padding, so here's both:
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.
 
Here's a simple inline routing to accomplish what you ask:

my $var="1234";

while (length($var)<20) { $var=&quot; &quot;$var; }

===========

If you want the sapces to the right then just swap the sequence of &quot; &quot;$var to $var&quot; &quot; and it will work every time.

 
That will work too, but using a while loop to accomplish that, and using the length function multiple times, and having to lengthen the string multiple time probably isn't very efficient. You could easily inline the code from one of the subroutines and it would be more efficient. 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