in reply to Split without removing characters

another way:
my $foo = "Hello WorldFoo BarPerl MonksSlash Dot"; for ($foo) { s/([a-z])([A-Z])/$1|$2/g; for (split /\|/ ) { print "$_ \n"; } }

Replies are listed 'Best First'.
Re^2: Split without removing characters
by cmeyer (Pilgrim) on Jun 17, 2005 at 19:57 UTC

    I don't care for this approach, because it fails as soon as $foo comes with embedded pipe characters. Then you have to think about escaping existing pipe characters, and so on, until you've reinvented CSV.

    -Colin.

    WHITEPAGES.COM | INC

      Nevertheless, given a set of known data, or a one-time event, this will work just as well. Not that I'm particularly a fan of it either, but it is another way to do it.
      Whilst a good point, it would have been helpful to add that a character other than a pipe character could be substituted, thereby avoiding the problem whereby $foo comes with embedded pipe characters. In fact you could use a complex string which you feel is almost guaranteed not to occur!

      e.g.

      my $sepstring = '7c6xb1%$#!@#$!@'; my $foo = "Hello WorldFoo BarPerl MonksSlash Dot"; for ($foo) { s/([a-z])([A-Z])/$1$sepstring$2/g; for (split /\Q$sepstring\E/ ) { print "$_ \n"; } }

        I wonder why you defend an approach that is more complex, less efficient, and prone to a problem that is "almost guaranteed not to occur", when there is a simple approach that is guaranteed not to have such a problem?

        -Colin.

        WHITEPAGES.COM | INC