To strip spaces from the beginning of the string:

$string =~ s/^\s+//;

To strip spaces from the end of the string:

$string =~ s/\s+$//;

I recall that someone showed a while back that it is more efficient to run these two statements sequentially rather than combining them into one statement like:

$string =~ s/^\s+|\s+$//g;

To find out more about regular expressions, you should be able to run the command perldoc perlre to see what your version of Perl has to offer.

To find out whether anything is left in the string you just have to do something like:

if( length($string) > 0 ) { # do something }

If you want to start chopping up strings, substr is your friend.

if( length($string) > 50 ) { # cut the string and either add ... to show it was truncated. $string = substr( $string, 0, 47 ) . '...'; # alternatively, or not $string = substr( $string, 0, 50 ); }

Seeing how you have used 50 in two places, it is good practice to put the 50 in a variable and then refer to that. That way, when you decide that you want to cut strings at 45 or 60 characters, you only have to change your code in one place.

my $MAXLEN = 50; if( length($string) > $MAXLEN ) { # cut the string and either add ... to show it was truncated. $string = substr( $string, 0, $MAXLEN-3 ) . '...'; # alternatively, or not $string = substr( $string, 0, $MAXLEN ); }

I personally would do a use constant (i.e. use constant MAXLIM => 50) but it is a fact that it gives a lot of people the heebie-jeebies around here, mainly because interpolating a constant into string is ugly.


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

In reply to Re: Searching Strings for Characters by grinder
in thread Searching Strings for Characters by Anonymous Monk

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.