[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] cut



On Wed, 13 Dec 2000 19:53:59 +0900, Matthias Dorn wrote:

>I am looking for a way to extract multiple occurances of a substring (in my 
>case something in rectangular brackets /^<.+$>/ in such a way that the 
>resultant list includes the brackets and its content.
>
>for example if i do a split at ">" somehow it gets cut of ?

Use lookahead and/or lookbehind. MacPerl is based on a reasonably old
Perl, so not all of that functionality is already built-in. But
lookahead seems to be working.

	
	$_ = "before>after";
	@a = split /(?=>)/;	# match in front of a ">"
	$\ = "\n"; $, = '^'; print @a;
-->	
	before^>after

That does mean that it will always match before such a character, not
after it, as lookbehind would have allowed.

	split /(?<=>)/  # match right after a ">"
			# doesn't work with MacPerl

If it would have worked, you would have gotten:

	before>^after

There are a few other hacks you can do. For example, if you capture what
you match, you can always append it to the string in front of right
after it.

	$_ = "before>after";
	$\ = "\n"; $, = '^';
	print split /(>)/;
-->
	before^>^after

A second hack, is a loop which emulates the behaviour of $` and $',
through split.

	$_ = 'before<inside>after';
	while(defined and (my($pre, $it), $_)
	  = split /(>)|(?=<)/, $_, 2){
	    defined $it	or $it = '';
	    print "$pre$it\n";
	}
-->
	before
	<inside>
	after

Note that I use lookahead to match "<", so it isn't eaten, but I do eat
the ">" which is captured into $it, and appended to the pre-match $pre.

True, lookbehind would have allowed a neater solution:

	@segments = split /(?=<)|(?<=>)/


p.s. I'm a bit puzzle to why the split on /(?=<)/ seems to skip a match
on the first character position. I would have expected the above code to
run in an endless loop, eternally matching a leading "<" but never
eating it.

-- 
	Bart.

# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org