> 
> Hi,

Hello,

> I need to format a string in a fixed width field. The string
> may be less than the length of the format, or may be greater.
> If less, then it should get  padded with spaces (left or right
> justified , like using - in sprintf), if greater, then the
> string should get truncated to the exact length.
> 
> eg $myVar = 'ABCDEFGHIJKLMNOP';
> $newVar = sprintf("%10s,$myVar);
> $newVar should have 'ABCDEFGHIJ'; # But has the full length i.e. 'ABCDEFGHIJKLMNOP'
> 
> eg $myVar = 'ABCD'; (Right Aligned, padded with spaces)
> $newVar = sprintf("%10s,$myVar);
> $newVar should have '      ABCD'; # Works
> 
> eg $myVar = 'ABCD'; (Left Aligned, padded with spaces)
> $newVar = sprintf("%-10s,$myVar);
> $newVar should have 'ABCD      '; # Works
> 
> I am not able to lay my finger on the correct format to achieve
> 1st and the 2nd with the same format. Am I missing something ,
> or is there another way out? Any help would be greatly appreciated.



>Fun with sprintf.  :-)

>$ perl -le'
>for $word ( qw/ABCDEFGHIJKLMNOP ABCD/ ) {
>    $string = sprintf q/%10.10s  %-10.10s  %10s  %-10s/, ($word) x 4;
>    print $string;                                                                 
>    $string = sprintf q/%*.*s  %-*.*s  %*s  %-*s/, (10,10,$word) x 2, (10,$word) x 2;
>    print $string;
>    }
>'
>ABCDEFGHIJ  ABCDEFGHIJ  ABCDEFGHIJKLMNOP  ABCDEFGHIJKLMNOP
>ABCDEFGHIJ  ABCDEFGHIJ  ABCDEFGHIJKLMNOP  ABCDEFGHIJKLMNOP
>      ABCD  ABCD              ABCD  ABCD      
>      ABCD  ABCD              ABCD  ABCD      


Thanks to Mark, John, David and Timothy....!! I get the results if I use the 
combination of 

eg $myVar = 'ABCDEFGHIJKLMNOP';
$newVar = pack('A10',$myVar);
$newVar should have 'ABCDEFGHIJ'; # Works and faster than sprintf

eg $myVar = 'ABCD';
$newVar = pack('A10',$myVar);
$newVar should have 'ABCD      '; # Works and faster than sprintf
 
eg $myVar = 'ABCD'; (Right Aligned, padded with spaces)
$newVar = sprintf("%-10.10s, $myVar);
$newVar should have '      ABCD'; # Works. Have to use sprintf as nothing available 
for right justify in pack.


Think pack is an elegant way of truncating a string.

Thanks
Shishir 




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to