Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl split function - consecutive delimiters

I am using the split function to split each record in a file. Say, the delimiter is $.

my @fields = split(/\$/,$record);

If each record has 4 fields, and if some fields are empty, there are 2 consecutive dollar symbols, like below:

abc$efg$ehd$rty
abc$$$

split doesn't work for the second record, since after the split, there are only 2 fields, instead of 4.

Any idea how to fix this, or if there are better options?

like image 563
Chris Avatar asked Dec 21 '22 18:12

Chris


1 Answers

From the split documentation:

If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified.

What this means is if you do something like:

my @fields = split( /\$/, $record, -1 );

...then you'll get empty fields for your last three entries in the list.

#!perl

use strict;
use warnings;
use Data::Dumper;

my $string = 'abc$$$';
my @fields = split( /\$/, $string, -1 );
print Dumper \@fields;

This prints:

$VAR1 = [
          'abc',
          '',
          '',
          ''
        ];
like image 110
CanSpice Avatar answered Jan 01 '23 23:01

CanSpice