[LA.pm] String handling like C array

Benjamin J. Tilly ben_tilly at operamail.com
Mon Feb 6 23:40:27 PST 2006


Robin Rowe" <rower at movieeditor.com> wrote:
> 
> Peter,
> 
> > You're looking to learn regular expressions.
> 
> Actually, I should have said that I'm not. Regex can be very useful, but
> sometimes I'd rather not. My C example was only to illustrate the idiom.
> Didn't mean to mislead anyone to think I'm really swapping 'x' and 'y'
> in a string.

I suspect that regular expressions can do more than you think.

> The Perl books tend to show only regex examples. Sometimes, I just want
> to walk the string. One reason is that I may be passing the string to a
> system call. The consequences of a bug in my use of regex can be too big
> a risk. And sometimes regex isn't powerful enough, that it can't
> implement branching algorithms.

It sounds like you want to use the regular expression engine as a
tokenizer.  With pos() and the /gc flag, you can.

Take a look at the implementation of _get_row and _get_quoted in my
Text::xSV for an illustration of the technique.

Also note that with the extensions that Perl's RE engine has, it
actually CAN implement branching algorithms.  However using the
(?>...) construct to do it is very ugly, and the information density
in the resulting expression turns your code into white noise.

> > Typically, 10 lines of C string code is just 1 line of perl.
> 
> Possibly, but I don't write typical C code. ;-)

Even so, if you know both languages well, you can generally write
things more compactly in Perl than C.

> Funny story, I once had a discussion with a Scheme evangelist who said
> C++ is always more lines of code for the same problem. I said fine, try
> me. He named a homework problem from some Scheme course. I was able to
> implement (correctly) with fewer lines of C++ than he did in Scheme.
> However, the algorithm in my solution was completely different and
> required an understanding of combinatoric number theory. He said it was
> unfair, that nobody could be expected to understand my C++ code. I said
> I felt the same way about Scheme! ;-)

I suspect that your algorithm could have been implemented in
Scheme more compactly than you implemented it in C++. :-)

Anyways Scheme isn't that hard to read once you get past the
initial shock.

> The motivation for me to use Perl is for portable glue code (to avoid
> bash/bat for pipeline scripts) and for web cgi where compiling is
> inconvenient.
[...]

Join the club. :-)

Cheers,
Ben


More information about the Losangeles-pm mailing list