Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: How to delete trailing spaces from array elements?

by radiantmatrix (Parson)
on Jul 31, 2007 at 14:14 UTC ( [id://629837]=note: print w/replies, xml ) Need Help??


in reply to How to delete trailing spaces from array elements?

There's a pretty common pattern for solving this, and it looks like this:

for (@arr1) { #for each element in @arr1 s/\s+$//; #replace one or more spaces at the end of it #with nothing (deleting them) }

You'll commonly see the regular expression s/^\s+|\s+$//g as well -- which basically says "match any whitespace at the beginning or end of the string, and remove all of it".

The shorter versions you see near the top of this discussion are simply shorter ways to write this pattern. In Perl, there's always more than one way to do things. To demonstrate that, here's another solution that would work (but I don't recommend):

for (@arr1) { while ( substr($_,-1,1) eq ' ' ) { # while the last char is space chop(); # remove the last char } }

Or, the shorter version:

for (@arr1) { chop() while substr($_,-1,1) eq ' ' }
<radiant.matrix>
Ramblings and references
The Code that can be seen is not the true Code
I haven't found a problem yet that can't be solved by a well-placed trebuchet

Replies are listed 'Best First'.
Re^2: How to delete trailing spaces from array elements?
by ysth (Canon) on Jul 31, 2007 at 19:25 UTC
    for(@arr1){1while' 'eq($c=chop);$_.=$c}

      Ok, if you insist:

      $/=' ';for(@arr1){1while chomp}

      Is 8 chars shorter. ;-)

      <radiant.matrix>
      Ramblings and references
      The Code that can be seen is not the true Code
      I haven't found a problem yet that can't be solved by a well-placed trebuchet

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-24 15:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found