in reply to keeping split deliimiters causing empty string elements

As BrowserUk and Athanasius have both shown, the best way to deal with the problem (in split and in regex matching in general) is not to have unmatched capture groups, which return undef, in the first place.

Sometimes, you're just gonna have capture groups that don't and won't match. The Perl version 5.10 Extended Patterns  (?|pattern) "branch reset" operator is very handy for this:

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $eqn = '$profit=$sales-$cogs'; my @wrds = split /(?|(=)|(-))/, $eqn; dd \@wrds; " ["\$profit", "=", "\$sales", "-", "\$cogs"]
If you don't have access to 5.10 or in general need to remove undefined (or zero-length, or whatever...) elements from a list, there's always grep:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $eqn = '$profit=$sales-$cogs'; my @wrds = grep defined, split /(=)|(-)/, $eqn; dd \@wrds; " ["\$profit", "=", "\$sales", "-", "\$cogs"]

Update: Revised wording; meaning unchanged.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: keeping split deliimiters causing empty string elements
by previous (Sexton) on Apr 15, 2016 at 17:58 UTC
    Thank you very much indeed for the pointers...for further reading. That's extremely helpful.