in reply to split with separators but dont include in the array

You're using lookahead and capturing parentheses. You want an unparenthesized expression so the separators are discarded.
@arr = split /&&|\|\|/, $str;

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: split with separators but dont include in the array
by anniyan (Monk) on Oct 17, 2005 at 15:44 UTC

    Roy Johnson and ikegami thanks for your quick replies. Here i have one question. First i tried like the following.

    @arr = split /(&&|\|\|)/, $str;

    But it included && and || in the array. Then only i went for lookahead option.

    But as per yours reply it works fine if i remove that extra grouping.

    @arr = split /&&|\|\|/, $str;

    Why is it so? Could you please explain. Then if there is many separators how to with that?

    Regards,
    Anniyan
    (CREATED in HELL by DEVIL to s|EVILS|GOODS|g in WORLD)

      Anything in capturing (plain) parentheses will be returned as a separate item in the split results. If you need parentheses for grouping, use non-capturing parentheses, which open with (?: instead of just (.

      No matter how many alternative separators you have, you don't need parentheses at all unless the alternatives are only part of the separator and you need to "factor out" common substrings. For example, if your valid separators were "foo&&", "foo||", and "++", you could split on

      /foo(?:&&|\|\|)|++/

      Caution: Contents may have been coded under pressure.
      @arr = split /(&&|\|\|)/, $str;
      But it included && and || in the array.

      That's because you used capturing parentheses.

      Then if there is many separators how to with that?

      You use the pipe "|" character to separate multiple options, like so:
      @arr = split /foo|bar|meh/, $str;
      That would split the string on any occurrences of "foo", "bar" or "meh" without including them in the resultant list.
      This may not be clear in your original example, as one of the strings you are splitting on is a double-pipe "||", so the escaping of those adds a bit of "noise" to the split expression :)
      The manual (split in this case) can usually dissipate such doubts:
      If the PATTERN contains parentheses, additional list elements are created from each matching sub- string in the delimiter. + split(/([,-])/, "1-10,20", 3); + produces the list value + (1, '-', 10, ',', 20)

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.