perl split

J

James

This I understand,
$ perl -le '@a=split//,"abc"; print $#a; print for(@a)'
2
a
b
c

But why this behavior?
$ perl -le '@a=split/(.)/,"abc"; print $#a; print for(@a)'
5

a

b

c

TIA
-James
 
D

Dr.Ruud

This I understand,
$ perl -le '@a = split //, "abc"; print $#a; print for @a'
2 [...]

But why this behavior?
$ perl -le '@a = split /(.)/, "abc"; print $#a; print for @a'
5 [...]

See perldoc -f split, look for 'parentheses'.
 
K

Klaus

But why this behavior?
$ perl -le '@a=split/(.)/,"abc"; print $#a; print for(@a)'
5

a

b

c

Looks normal to me: you split with any character as separator, so you
get:

- an empty string before the separator 'a'
- then, because you have put brackets into the regex, the separator
('a' in this case) is added
- then another empty string between the two separators 'a' and 'b'
- then, again, you have put brackets into the regex, so you get the
second separator ('b' in this case)
- then yet another empty string between the two separators 'b' and 'c'
- finally you get the last separator 'c'
 
J

John W. Krahn

Klaus said:
Looks normal to me: you split with any character as separator, so you
get:

- an empty string before the separator 'a'
- then, because you have put brackets into the regex, the separator
('a' in this case) is added
- then another empty string between the two separators 'a' and 'b'
- then, again, you have put brackets into the regex, so you get the
second separator ('b' in this case)
- then yet another empty string between the two separators 'b' and 'c'
- finally you get the last separator 'c'

And finally you get the last empty string between 'c' and the
end-of-string, which is discarded because it is a trailing empty string.
If you want to see it use a negative number as the third argument to
split:

$ perl -le '@a=split/(.)/,"abc",-1; print $#a; print for(@a)'
6

a

b

c




John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top