in reply to Alternative to substr on unknown length of scalar
Why do you not, in place of the if statement, just do: $conv = sprintf("%6f" substr($line, 0, 6));. In the case of a string longer than 6 characters, it returns only the leftmost 6 characters; in the case of a string shorter than 6 characters, it returns a string padded on the left with spaces.
Testing:
$ # String longer than 6 characters $ perl -e '$a="1234567"; $b=sprintf("%6s", substr($a, 0, 6)); print $b +;' 123456 $ # String shorter than 6 characters $ perl -e '$a="123"; $b=sprintf("%6s", substr($a, 0, 6)); print $b;' 123 $ # Example of results from OP's code $ perl -e '$a="1234567"; $b=substr($a, 0, 6); print $b;' 123456 $ perl -e '$a="123"; $b=sprintf("%6s", substr($a, 0)); print $b;' 123
Hope that helps.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Alternative to substr on unknown length of scalar
by PerlingTheUK (Hermit) on Oct 19, 2004 at 07:55 UTC |