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

Hi all, I have a string scalar which has one or more text called "command". For example :
command = adb asd 2t525 command=adfaf adsgadg asd
How do you split the following scalar using regular expression into array by pattern "command" but preserve the word "command" in each elements in the array?

best regards

kevin

Replies are listed 'Best First'.
Re: split but preserve the matching pattern
by artist (Parson) on Feb 25, 2005 at 05:42 UTC
    $data =<<EOL; command = adb asd 2t525 command=adfaf adsgadg asd EOL @commands = split /(?=command)/,$data; foreach (@commands){ print "$_\n"; print "==========\n"; }
    Gives
    command = adb
    asd
      2t525
     
    ==========
    command=adfaf
      adsgadg
    asd
    
    ==========
    
Re: split but preserve the matching pattern
by bobf (Monsignor) on Feb 25, 2005 at 05:48 UTC

    I'm not sure I understand exactly what you are looking for, but here's my best guess. This splits the text you provided on the word "command", retains the pattern in the results, and spans newlines. If you're looking for something else (e.g., splitting only lines containing "command"), please be more specific and we can go from there.

    use strict; use warnings; use Data::Dumper; my $string = "command = adb asd 2t525 command=adfaf adsgadg asd"; my @results = split( /(?=command)/, $string ); print Dumper( \@results );
    The @results array contains two elements:
    $VAR1 = [ 'command = adb asd 2t525 ', 'command=adfaf adsgadg asd' ];
    HTH

Re: split but preserve the matching pattern
by gopalr (Priest) on Feb 25, 2005 at 06:28 UTC

    Hi nwkcmk,

    $text=' command = adb asd 2t525 command=adfaf adsgadg asd '; @arr=$text=~m#(command\s*=\s*[^\n]+)\n#gs; print "\n@arr";
Re: split but preserve the matching pattern
by friedo (Prior) on Feb 25, 2005 at 05:45 UTC
    You could probably do it much easier with a global match, but here's what I came up with for split:

    my $a="command = adb asd 2t525 command=adfaf adsgadg asd "; my @t = map { "command" . $_ } grep { $_ ne "" } split /command/, $a; print @t;
Re: split but preserve the matching pattern
by nwkcmk (Sexton) on Feb 25, 2005 at 06:32 UTC
    Hi folks,

    Thanks to the help. I never use ?= before but know how to use it now.

    best regards

    kevin