Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Split confusion

by kcott (Archbishop)
on Jun 04, 2020 at 08:30 UTC ( [id://11117690]=note: print w/replies, xml ) Need Help??


in reply to Split confusion

G'day swampyankee,

"I was expecting ... "SMITH", "-", "JONES" ... I got "S","","M","", ... What did I do wrong?"

The documentation for split describes what happens with capturing. The section at the end (starting with "If the PATTERN contains capturing groups, ...") has a description followed by several examples.

Here's your regex without capturing:

$ perl -E 'say "|$_|" for split /-| /, "A B-C"' |A| |B| |C|

Now with capturing (and what I think you intended):

$ perl -E 'say "|$_|" for split /(-| )/, "A B-C"' |A| | | |B| |-| |C|

If you coded /(-|)/ instead of /(-| )/, you would get the output you're seeing:

$ perl -E 'say "|$_|" for split /(-|)/, "A B-C"' |A| || | | || |B| |-| |C|

That, of course, is just a guess; however, given other issues (already noted by hippo) in your posted code, possibly a good guess.

"The split's documentation seems to say that / / doesn't split between every character, but " " does."

I expect you've misread or misunderstood something. Had you quoted the text that you thought seems to say what you suggest, I could comment further. There can be errors in documentation and those errors can be fixed; perhaps there's not an error but a clarification of the current text would help — obviously, the source of the confusion needs to be identified as a first step.

Anyway, neither / / nor " " will "split between every character":

$ perl -E 'say "|$_|" for split / /, "A B-C"' |A| |B-C| $ perl -E 'say "|$_|" for split " ", "A B-C"' |A| |B-C|

Without the spaces, both will "split between every character":

$ perl -E 'say "|$_|" for split //, "A B-C"' |A| | | |B| |-| |C| $ perl -E 'say "|$_|" for split "", "A B-C"' |A| | | |B| |-| |C|

Regardless, I don't see how / / or " " relate to /(-| )/.

— Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-03-28 18:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found