Welcome to the Monastery!

If you want to do it in one statement, you can do this:

my $val = " Smart Way "; $val =~ s/^\s+|\s+$//g; print '>', $val, '<';

You asked for a one-line solution. That will do it. A better solution (still using s///) is two lines, since alternation is expensive if you value time efficiency.

I feel somewhat guilty for having retyped an answer that has been provided right at our fingertips in the Q&A section under the heading, How do I remove whitespace at the beginning or end of my string?. If you look there you'll see a lot of different alternatives of which one is sure to be right for any occasion. ;) This being your first post I just want to encourage you to familiarize yourself with the more helpful aspects of the Monastery such as the Q&A section, and the Tutorials section. The Q&A section is a FAQ of sorts; not a place to post questions, but rather, a place to post answers to common questions. You'll find a wealth of information there, most good, some just ok, but all there for edification. It also is a great idea to become familiar with the perldocs. If you have Perl, you have the perldocs. If you prefer reading them online, you can find them right here in the Monastery as well. Enjoy!

Oh, this isn't related to your question, but rather, to the presentation of your question. I wanted to mention that you don't need to use <br> tags to create new lines within <code></ code> tags. Take a look at how your original post looks and you'll see what I mean. You did preview right?

Dave

"If I had my life to do over again, I'd be a plumber." -- Albert Einstein


In reply to Re: remove both leading and trailing spaces by davido
in thread remove both leading and trailing spaces by s_mile

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.