I want to split a string(which has numerical digits). In the below example, I want to split the string at k and k1.
my @array1=("0","23","1","4","65","7");
$k=1;$k1=0;
my $j=join("",@array1);
my @ar=split(/($k|$k1)/,$j);
print join(";",@ar),"\n\n";
The output is ;0;23;1;4657
In the above output, extra semicolon “;” is printing
The expected output is 0;23;1;4657
When I try the above code for the below example, the output is correct: (0;5;123;4;6); the extra semicolon is not printing here.
my @array1=("0","5","1234","6");
$k=5;$k1=4;
I am not sure, for what reason the first example is printing extra semicolon “;”
Can some one help me in this?
The difference is when you split around the first character, you get an empty value at the beginning. Hence the extra ; before the 0 (and after the “”). You’ll similarly find ;; when splitting on two adjacent characters
So the absolute simplest fix would be to use grep to remove empty string:
This removes the empty strings in @ar.
In the bigger picture, you might want to look at why you’re joining strings just to split them back apart. You’re also splitting around a number in one place that could appear in another. Like if $k=1 and @array1 = (11, 23, 1, 4);