G'day MrSnrub,
I see you have a lot of responses already. Here's my take on this.
You can trim the data by capturing everything that isn't leading or trailing whitespace with this regular expression:
/\A\s*(.*?)\s*\z/
You can use that directly inside a map like this:
say for map { (/\A\s*(.*?)\s*\z/) } split /\|/, $str;
You can use it inside a subroutine called from map like this:
say for map { clean($_) } split /\|/, $str;
sub clean { ($_[0] =~ /\A\s*(.*?)\s*\z/)[0] }
It's good that you've tried a variety of cases with whitespace in different positions in your test input $str. What you don't have is leading whitespace at the start of $str or trailing whitespace (following non-whitespace) at the end of $str.
Here's my tests using both of the options I presented with some additional test data.
$ perl -Mstrict -Mwarnings -E '
my $str = " \t item0 with leading whitespace |item1 | item2| item3
| extra item with embedded whitespace \t \n \n\t
|item4|
| itemN with trailing whitespace \t
";
say "---- WITHOUT SUBROUTINE ---";
say ">$_<" for map { (/\A\s*(.*?)\s*\z/) } split /\|/, $str;
say "---- USING SUBROUTINE ---";
say "<$_>" for map { clean($_) } split /\|/, $str;
sub clean { ($_[0] =~ /\A\s*(.*?)\s*\z/)[0] }
'
---- WITHOUT SUBROUTINE ---
>item0 with leading whitespace<
>item1<
>item2<
>item3<
>extra item with embedded whitespace<
>item4<
><
>itemN with trailing whitespace<
---- USING SUBROUTINE ---
<item0 with leading whitespace>
<item1>
<item2>
<item3>
<extra item with embedded whitespace>
<item4>
<>
<itemN with trailing whitespace>
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.