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.
In reply to Re: Alternative to substr on unknown length of scalar
by atcroft
in thread Alternative to substr on unknown length of scalar
by PerlingTheUK
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |