Variables as min,max in regular expression

D

David Frauzel

Quick question.

I have this regexp:

s/(.{$descmin,$descmax} ).*/$1.../

The purpose is to trim a long string by adding '...' at the end of a
truncated version (after the last full word), using $descmin and $descmax
to determine how long the truncated string can be.

This doesn't seem to behave as I thought it ought. Using digits it works
quite nicely:

s/(.{40,50} ).*/$1.../

But introducing the variables seems to confuse the regexp - although I'm
not sure. The documentation (perlre) doesn't seem to address this (or if
I've missed it, please point me to the relevant paragraph!), and my only
other source of "information" is Komodo's Rx Toolkit, which informs me
that it is attempting to match literal '{', literal 'descmin', literal
'descmax', and the dollars are 'end of string'.

Can I not use variables to describe the min and max in a match count
clause?
 
S

Steve Grazzini

David Frauzel said:
The documentation (perlre) doesn't seem to address this (or if I've
missed it, please point me to the relevant paragraph!), and my only
other source of "information" is Komodo's Rx Toolkit, which informs me
that it is attempting to match literal '{', literal 'descmin', literal
'descmax', and the dollars are 'end of string'.

Can I not use variables to describe the min and max in a match count
clause?

Sure you can. Maybe Komodo is interfering somehow...

$ perl -le '($x,$y) = (1,2); print for "foo" =~ /.{$x,$y}/g'
fo
o

The docs for this (in perlop: the "Gory details of parsing quoted
constructs") confirm that variable interpolation comes before the
compilation of the regex.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top