ultranerds has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I'm just trying to see if this is possible. I wanna do this:

my @values = split /[\.,;\!]/, $something;

So it will split the string at either . , ; or !

Now, the code above should be fine for that - but is there any way to "save" the charachter it split at somehow?

Basically, once its been split - I need to re-build it properly when joining the arrray together.

Hopefully that makes sense :)

TIA

Andy

Replies are listed 'Best First'.
Re: Possible to use "split", but save the delimiter?
by BrowserUk (Patriarch) on Feb 08, 2010 at 14:34 UTC

    If you capture bracket the split regex, the delimiters will be retained:

    $s = "this.that,the other; and this! as well";; @bits = split /([.,;!])/, $s;; $_ !~ /[.,;!]/ and $_ = uc for @bits;; print join'',@bits;; THIS.THAT,THE OTHER; AND THIS! AS WELL

    A pointless example, but it demos the technique.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Possible to use "split", but save the delimiter?
by toolic (Bishop) on Feb 08, 2010 at 14:52 UTC
    Yes, it is possible, and it is even documented in split:
    If the PATTERN contains parentheses, additional list elements are created from each matching substring in the delimiter.
    1. split(/([,-])/, "1-10,20", 3);
    produces the list value
    1. (1, '-', 10, ',', 20)
      Thanks, will give those a go :)

      Cheers!

      Andy
      Hi,

      This almost works:

      my $test = qq|1-10,20 some.thing [[else]],bla bla bla|; my @temp = split /([,-\s\.\]\[]+)/, $test; use Data::Dumper; print Dumper(@temp);


      ..but for some reason, it doesn't seem to like the ]] bit :

      1 - 10 , 20 some . thing [[ else ]], bla bla bla


      We need it to split at:

      [[ ]] , - \s .


      Any suggestions?

      TIA!

      Andy

        This what you're after?

        $s = qq|1-10,20 some.thing [[else]],bla bla bla|;; print "'$_'" for split /([-, .]|\[\[|\]\])/, $s;; '1' '-' '10' ',' '20' ' ' 'some' '.' 'thing' ' ' '' '[[' 'else' ']]' '' ',' 'bla' ' ' 'bla' ' ' 'bla'

        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Possible to use "split", but save the delimiter?
by jwkrahn (Abbot) on Feb 08, 2010 at 20:27 UTC
    my @values = $something =~ /[^.,;!]*[.,;!]/g;