The first problem with this code is indeed the fact that grep's purpose is selection, not modification, so it does not help readability. But the problem mentionned by LanX is the worst I guess, that @x is modified under the hood, without it being explicit in the function description is a serious issue.

If modifying @x is OK, then there's no need for another array and s/^\s*|\s*$/g for @x would avoid the copy of the array.

Or, since map can actually do both modification and selection (it can yield a list of one, zero or more values for each input value) here's another way to do the same thing: @y = map { /(\S.*\S)/ ? $1 : () } @x; or if using map to remove elements isn't clear enough: @y = grep defined, map /(\S.*\S)/, @x;

Edit: Whoops, doesn't work for strings that contain only one non-space char. /(\S.*?)\s*$/ would work but is not as easy to read.


In reply to Re: Code review: function to trim whitespace from all items in a list by Eily
in thread Code review: function to trim whitespace from all items in a list by eyepopslikeamosquito

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.