in reply to How to split a string based on the length of a sequence of characters within the string
The regex you provide to split specifies a separator, so Perl is splitting your string into chunks separated by sequences of ten characters each. What you get is the following:
$VAR1 = [ <chunk1>, <separator>, <chunk2>, <separator>, <chunk3>, <separator>, <chunk4>, <separator>, <chunk5> ]
And all the chunks are empty except for the last one, which makes sense since there are no constraints on the separators (other than their length): Perl searches for the separator, finds it right at the beginning of the string, and splits it off along with a preceding empty chunk; then the whole process repeats, until you've only got five characters left, not enough to match the separator, so that's your last chunk.
Here's how I'd split a string into ten-character chunks using a regex:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $input = "1234567890abcdefghij0987654321ABCDEFGHIJlmnop"; my @chunks = ($input =~ /.{1,10}/g); print Dumper \@chunks;
This produces:
$VAR1 = [ '1234567890', 'abcdefghij', '0987654321', 'ABCDEFGHIJ', 'lmnop' ];
Note that the quantifier needs to be {1,10} rather than just {10} here to accomodate the final chunk of less than ten characters. The regex engine's greediness will ensure that all chunks but the last will get the full ten characters.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to split a string based on character(s) length
by thanos1983 (Parson) on Aug 13, 2014 at 20:14 UTC | |
by AppleFritter (Vicar) on Aug 13, 2014 at 20:37 UTC |