1

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);
8
  • 1
    Why would you think you need to initialize elements in an array? Commented Jun 10, 2013 at 21:30
  • You can initialize $n elements of @fields... but as TLP says, why would you want to? You can trust Perl to give you undef if you read from an uninitialised part of the array, you won't get random memory contents. Commented Jun 10, 2013 at 21:34
  • @JamesGreen At line 3 in this code, it doesn't matter what he initialized: The entire array is overwritten anyway. Commented Jun 10, 2013 at 21:34
  • Well, yeah, that too :-) Commented Jun 10, 2013 at 21:35
  • 2
    Also, '-' x $n would create the string ------..., not add elements to the array. You'd need this syntax for that ('-') x $n. Commented Jun 10, 2013 at 22:32

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

defined $_ ? $_ : '-' can also be written as $_ // '-'
split never returns undef, unless there are capturing parentheses in the split regex that end up not being used as part of the match (e.g. split /(x)?/, "ab" returning "a",undef,"b")
0

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 ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.