in reply to Remove whitespace in string and maintain overall length

toolic's solution is pretty good, though for padding I usually prefer making that padding obvious:
my $address = "$strnum $strname $strtype $strdir"; $address =~ s/\s+/ /g; $address .= ' ' while length $address < 37;
Note that I've also made the code agnostic as to the kind of whitespace.

That approach has a lot more operations, but reads easily. Another question to consider is are address guaranteed to be less than 38 characters, and if not should you truncate. So you might do that one as

my $address = sprintf '%-37.37s', "$strnum $strname $strtype $strdir" +=~ s/\s+/ /rg;
where I've truncated to 37, used sprintf and the r modifier, and put it on one line to make it as inobvious as possible.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Remove whitespace in string and maintain overall length
by silentbob343 (Initiate) on Nov 19, 2015 at 19:25 UTC

    Your first solution is more inline with what I thought would need to be done, some kind of length interrogation, and very readable as well.

    I am somewhat lucky in that the data being pulled will have a max length of 37 as that was the max length of the various fields used to build the free form address. The source of those fields won't change anytime soon without a overhaul of our current systems.

    To your point though a check like that can never hurt, thanks for that.