split has already been recommended, but you need to be aware of the default behavior of split with respect to empty leading or trailing fields.
From the docs,
By default, empty leading fields are preserved, and empty trailing ones are deleted. (If all fields are empty, they are considered to be trailing.)
...
If LIMIT is specified and positive, it represents the maximum number of fields the EXPR will be split into, though the actual number of fields returned depends on the number of times PATTERN matches within EXPR. If LIMIT is unspecified or zero, trailing null fields are stripped (which potential users of pop would do well to remember).
This behavior is illustrated in the following example:
use strict;
use warnings;
while( my $str = <DATA> )
{
chomp $str;
print "\nsplitting $str with these LIMITs:\n";
foreach my $limit ( 0, 5, 7, -1 )
{
my $result = munge( $str, $limit );
printf " %2d => [$result]\n", $limit;
}
}
sub munge
{
my ( $str, $limit ) = @_;
my @fields = split( '\|', $str, $limit );
@fields = map { $_ || 'empty' } @fields;
# using a different delimiter to illustrate non-split fields
return join( '!', @fields );
}
__DATA__
1|2|3|4|5|6
1|2||4||
|2|3|||
|||||
This produces the following output:
splitting 1|2|3|4|5|6 with these LIMITs:
0 => [1!2!3!4!5!6]
5 => [1!2!3!4!5|6]
7 => [1!2!3!4!5!6]
-1 => [1!2!3!4!5!6]
splitting 1|2||4|| with these LIMITs:
0 => [1!2!empty!4]
5 => [1!2!empty!4!|]
7 => [1!2!empty!4!empty!empty]
-1 => [1!2!empty!4!empty!empty]
splitting |2|3||| with these LIMITs:
0 => [empty!2!3]
5 => [empty!2!3!empty!|]
7 => [empty!2!3!empty!empty!empty]
-1 => [empty!2!3!empty!empty!empty]
splitting ||||| with these LIMITs:
0 => []
5 => [empty!empty!empty!empty!|]
7 => [empty!empty!empty!empty!empty!empty]
-1 => [empty!empty!empty!empty!empty!empty]
Note the effect on the empty leading and trailing fields when using a LIMIT of 0, a positive LIMIT less than the expected number of fields, a positive LIMIT greater than the expected number of fields, and a negative LIMIT.
For your application, I think you either want to specify a LIMIT that corresponds to the number of expected fields (if you know this in advance), or a negative LIMIT.
HTH
Update: graff++; # I suspected I was overdoing the example :-) |