More About split

Remember the split function, from Day 5, Working with Hashes?” We were using split to divide up names into first and last name lists, like this:

($fn, $ln) = split(" ", $in);

At the time, I explained that using split with a space in quotes was actually a special case that would only work on data in which fields were separated by whitespace. To use split for data separated by any other characters, or needing any kind of sophisticated processing to find the elements, you'll use split with a regular expression as the pattern to match on:

 ($fn, $ln) = split(/\s+/, $in); # split on whitespace @nums = split(//, $num); # split 123 into (1,2,3) @fields = split(/\s*,\s*/, $in); # split comma-separated fields, # with or without whitespace ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.