in reply to How to clean an array of strings after a split

Another approach depends on realizing that an expression like  my ($var1, $var2, ...) = ...; yields a list that can be processed with a Perl-ish for-loop.

>perl -wMstrict -le "my $str = 'a| b||c | 0 '; ;; $_ //= '' for my ($var1, $var2, $var3, $var4, $var5, $var6) = map Trim($_), split m{\|}xms, $str; ;; printf qq{'$_' } for $var1, $var2, $var3, $var4, $var5, $var6; ;; sub Trim { $_[0] =~ s{ \A \s+ | \s+ \z }''xmsg; return $_[0]; } " 'a' 'b' '' 'c' '0' ''

Use  defined or $_ = '' if you do not have the  //= operator (Perl 5.10+). Also, 5.14+ offers the  /r modifier for  s/// substitutions, which allows a slight simplification of the  Trim() function to
    sub Trim { return $_[0] =~ s{ \A \s+ | \s+ \z }''xmsgr; }

Also:
        ... am I correct in thinking that ... the parts of the string that are split will always be defined?
Yes.

Replies are listed 'Best First'.
Re^2: How to clean an array of strings after a split
by MrSnrub (Beadle) on Aug 29, 2013 at 15:37 UTC
    Thanks. I think I like this approach best because I don't need to concern myself with ensuring there are enough pipe symbols to suffice.

      Actually, if you used kcott's suggestion here and split into a named array, e.g.
          my @fields = map { ... } split ..., $str;
      you wouldn't have to worry about how many pipes there are and 'uninitialized' variables: you get what you get, it's all defined, and it's easy to test how much you've gotten by taking the size of the array and to iterate over the array. Rather than writing  $varn you write  $fields[n] instead, but 0-based.
      But I assume you have your reasons for preferring individual named variables...