P is for Practical | |
PerlMonks |
perlfunc:splitby gods (Initiate) |
on Aug 24, 1999 at 22:43 UTC ( [id://326]=perlfunc: print w/replies, xml ) | Need Help?? |
splitSee the current Perl documentation for split. Here is our local, out-dated (pre-5.6) version: split - split up a string using a regexp delimiter
split /PATTERN/,EXPR,LIMIT split /PATTERN/,EXPR split /PATTERN/ split
Splits a string into an array of strings, and returns it. By default, empty leading fields are preserved, and empty trailing ones are deleted.
If not in list context, returns the number of fields found and splits into
the
If
EXPR is omitted, splits the If LIMIT is specified and positive, splits into no more than that many fields (though it may split into fewer). If LIMIT is unspecified or zero, trailing null fields are stripped (which potential users of pop() would do well to remember). If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified.
A pattern matching the null string (not to be confused
with a null pattern
print join(':', split(/ */, 'hi there')); produces the output 'h:i:t:h:e:r:e'. The LIMIT parameter can be used to split a line partially
($login, $passwd, $remainder) = split(/:/, $_, 3); When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work. For the list above LIMIT would have been 4 by default. In time critical applications it behooves you not to split into more fields than you really need. If the PATTERN contains parentheses, additional array elements are created from each matching substring in the delimiter.
split(/([,-])/, "1-10,20", 3); produces the list value
(1, '-', 10, ',', 20)
If you had the entire header of a normal Unix email message in
$header =~ s/\n\s+/ /g; # fix continuation lines %hdrs = (UNIX_FROM => split /^(\S*?):\s*/m, $header);
The pattern
As a special case, specifying a
PATTERN of space ( Example:
open(PASSWD, '/etc/passwd'); while (<PASSWD>) { ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/); #... }
(Note that |
|