Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work around for split function when last character is a terminator

Tags:

split

perl

I have this line of data with 20 fields:

my $data = '54243|601|0|||0|N|0|0|0|0|0||||||99582|';

I'm using this to split the data:

my @data = split ('\|'), $data;

However, instead of 20 pieces of data, you only get 19:

print scalar @data;

I could manually push an empty string onto @data if the last character is a | but I'm wondering if there is a more perlish way.

like image 388
StevieD Avatar asked Feb 06 '23 03:02

StevieD


1 Answers

Do

my @data = split /\|/, $data, -1;

The -1 tells split to include empty trailing fields.

(Your parentheses around the regex are incorrect, and lead to $data not being considered a parameter of split. Also, with one exception, the first argument of split is always a regex, so it is better to specify it as a regex not a string that will be interpreted as a regex.)

like image 78
ysth Avatar answered Feb 08 '23 14:02

ysth