
davorg
Thaumaturge
/ Moderator
Nov 4, 2004, 5:11 AM
Post #3 of 3
(281 views)
|
|
Re: [babyBlue] why split failed
[In reply to]
|
Can't Post
|
|
Just a couple of points to back up what KevinR has already told you. Firstly, it's always worth looking at the documentation for any function that you are having. In this case, the docs for split make it clear that the first argument is interpreted as a pattern (also known as a regular expression), not a string. A dot has a special meaning in regular expressions - it means "match any character". Even tho' the first parameter doesn't look like it, it is still interpreted as a regex. I never use quotes to delimit the first argument to split as it is too easy to forget and think that it is a string. If you had written the expression as
@numbers = split(/./, "1.2.3.4"); Then I think it would have been easier to see your error. It's also worth looking at what exactly happened in your version of the code. The regex that split splits on is thrown away. For example iyou had code like:
my @numbers = split /,/, '1,2,3,4'; Then you wouldn't expect to see any comma characters left in the elements of @numbers. They would have been thrown away. It's the same with your code. You code says "split the string whenever you find any character and return a list of strings from between those characters". Now, by definition there can't be any characters left between "any character". So you get a list of "undef" values. By default Perl removes any trailing undefined elements from the list returned by split so you get an empty list. It might be interesting to compare your code with what you get if you force Perl to return all of the elements in the list (by giving split a negative third parameter).
# Based on your code - prints nothing print map { "<$_>" } split /./, '1.2.3.4'; # Forcing all empty elements print map { "<$_>" } split /./, '1.2.3.4', -1; In the second example you get a number of empty <> sequences printed out. One for each element in the return list. Hope this helps. Let me know if you need any more detail on any of this. -- Dave Cross, Perl Hacker, Trainer and Writer http://www.dave.org.uk/ Get more help at Perl Monks
|