Question about using split

Discussion in 'Perl Misc' started by Max Adams, Aug 29, 2003.

  1. Max Adams

    Max Adams Guest

    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
    Max Adams, Aug 29, 2003
    #1
    1. Advertising

  2. Max Adams

    Greg Bacon Guest

    In article <binuh4$bf0j0$-berlin.de>,
    Max Adams <> wrote:

    : 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
    --
    The engineers built a special instruction to encapsulate the function of [a
    sequence of frequently executed instructions], rebuilt the system, and found
    it made no difference at all; they had optimized the idle loop for the
    operating system. -- bwk and rob, *The Practice of Programming*
    Greg Bacon, Aug 29, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    453
  2. Carlos Ribeiro
    Replies:
    11
    Views:
    688
    Alex Martelli
    Sep 17, 2004
  3. trans.  (T. Onoma)

    split on '' (and another for split -1)

    trans. (T. Onoma), Dec 27, 2004, in forum: Ruby
    Replies:
    10
    Views:
    203
    Florian Gross
    Dec 28, 2004
  4. Sam Kong
    Replies:
    5
    Views:
    228
    Rick DeNatale
    Aug 12, 2006
  5. Stanley Xu
    Replies:
    2
    Views:
    591
    Stanley Xu
    Mar 23, 2011
Loading...

Share This Page