Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: keeping split deliimiters causing empty string elements

by AnomalousMonk (Archbishop)
on Apr 15, 2016 at 14:26 UTC ( [id://1160524]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1160524]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-04-20 00:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found