Question about using split

M

Max Adams

All I have a string which I want to split on the characters "SA", simple
enough, I also want to (in the same expression) split on "sa" just to catch
any lowercase characters, however I would like the characters SA/sa to
remain in the array after the split, it's simple enough to append it back
on, but it is a little clumsy and has caused some problems. Can anyone
suggest a solution?

PT
 
G

Greg Bacon

: All I have a string which I want to split on the characters "SA",
: simple enough, I also want to (in the same expression) split on "sa"
: just to catch any lowercase characters, however I would like the
: characters SA/sa to remain in the array after the split, it's simple
: enough to append it back on, but it is a little clumsy and has caused
: some problems. Can anyone suggest a solution?

Instead of split, try m//:

#! /usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

sub split_on_sa {
local $_ = shift;

my @parts;
while (/(.*?(SA|sa))/gc) {
push @parts => $1;
}

my $pos = pos || 0;
push @parts => substr($_, $pos) if $pos != length;

@parts;
}

for ("foo-sa-bar-SA-baz-Sa-quux", "abcSA", "123") {
print "$_:\n", Dumper [split_on_sa $_];
}

Output:

foo-sa-bar-SA-baz-Sa-quux:
$VAR1 = [
'foo-sa',
'-bar-SA',
'-baz-Sa-quux'
];
abcSA:
$VAR1 = [
'abcSA'
];
123:
$VAR1 = [
'123'
];

Hope this helps,
Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top