Reputation: 181
I have a string (e.g. '24G22') which I am trying to split into separate elements of numbers and character (i.e. 24, G, 22). For which, I wrote the regular expression as shown below.
However, for some weird reason, I get alot of undefined elements in my array which I had expected to be of the form:
@array = ('24','G', '22')
instead of
@array = ('24', undef, undef, 'G', '22', undef)
which I get from the output
Could someone help explain to me the cause of the error and how I could rectify the error and get my desired output?
Script
#!/usr/bin/perl
use strict;
use warnings;
my $string = '24G22';
my @array = ( $string =~ m/([0-9]+)|([ATGCN]+)/g );
print join("\n", @array);
Output
$ ./test_debug.pl
Use of uninitialized value $array[1] in join or string at ./test_debug.pl line 8.
Use of uninitialized value $array[2] in join or string at ./test_debug.pl line 8.
Use of uninitialized value $array[5] in join or string at ./test_debug.pl line 8.
24
G
22
Upvotes: 0
Views: 755
Reputation: 91488
Just group in one group:
my @array = ( $string =~ m/([0-9]+|[ATGCN]+)/g );
because you have to catch only one group for each match.
With yours, you're matching 2 groups each times and one of them is empty.
Upvotes: 1