Is there an easy way (other than iterating through each element) to initialize n elements of @fields if it is not defined or empty ?
my @fields = '-' x n;
$string = 'a|b||c';
@fields = split(/\|/,$string);
To create an array of n elements, you should rather use
my @fields = ('-') x $n;
Note the dollar sign and the parentheses.
I do not understand what you meant by the following two lines of the code. If you want $fields[2] to contain - after splitting, you can fix the string before splitting:
my $string = 'a|b||c';
$string =~ s/\|(?=\|)/|-/g;
my @fields = split /\|/, $string;
Or use map after it:
my $string = 'a|b||c';
my @fields = map length $_ ? $_ : '-', split /\|/, $string;
I'm guessing you may want to be initializing all fields not provided by the split? If so, you can do this:
my @fields = ( split(/\|/, $string), ('-') x $n )[0..$n-1];
or this:
my @fields = split /\|/, $string;
@fields[ @fields..$n ] = ('-') x ($n-$#fields);
or this:
my @fields = split /\|/, $string;
$_ = '-' for @fields[ @fields..$n ];
'-' x $nwould create the string------..., not add elements to the array. You'd need this syntax for that('-') x $n.