Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Remove whitespace in string and maintain overall length

by kennethk (Abbot)
on Nov 19, 2015 at 19:12 UTC ( [id://1148147]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1148147]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-16 08:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found