user1147654
user1147654

Reputation:

splitting on pipe character in perl

I have a little problem. I want to split a line at every pipe character found using the split operator. Like in this example.

echo "000001d17757274585d28f3e405e75ed|||||||||||1||||||||||||||||||||||||" | \
perl -ane '$data = $_ ; chop $data ; @d = split(/\|/ , $data) ; print $#d+1,"\n" ;'

I would expect an ouput of 36 as awk splitting with the delimiter | return 36, but instead I get 12, as if the split stopped at the 1 character in the line.

echo "000001d17757274585d28f3e405e75ed|||||||||||1|||||||||||||||||||||||||||||||||||||||" | \ 
awk -F"|" '{print NF}'

Any idea. I have tried many ways of quoting the |, but without success. Many thanks by advance.

Upvotes: 9

Views: 5277

Answers (1)

Mat
Mat

Reputation: 206765

According to split:

By default, empty leading fields are preserved, and empty trailing ones are deleted.

You need to specify a negative limit to the split to get the trailing ones:

split(/\|/, $data, -1)

Upvotes: 18

Related Questions