Is split what I want to use here or pop?

Viewed 157

I found out something strange about split. I guess it will not parse blank content until there is something at the end.

I have a string that splits at a comma. However, when there are repeated delimiters at the end, they will not be added to the array until there is something at the end like so:

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

my $str = "ABC,123,,,,,,"; # just ABC and 123
#my $str = "ABC,123,,,,,,this"; # now it shows the blanks.
my @elems = split ',', $str;
print Dumper \@elems;

Any other ways, such as regex? Or should I trick the array and then pop the last content out?

2 Answers

You can specify a negative LIMIT:

my $str = "ABC,123,,,,,,";
my @elems = split ',', $str, -1;

From split:

If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced.

If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped

Dumper output:

$VAR1 = [
          'ABC',
          '123',
          '',
          '',
          '',
          '',
          '',
          ''
        ];

For reference: a regular expression can assist in filling an array

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

my $str;
$str = 'ABC,123,,,,,,';         # just ABC and 123
#$str = 'ABC,123,,,,,,this';    # now it shows the blanks

my @elems = $str =~ /([^,]*),?/g;

print Dumper \@elems;

Output

$VAR1 = [
          'ABC',
          '123',
          '',
          '',
          '',
          '',
          '',
          ''
        ];
Related