From: dblack@... Date: 2006-07-16T01:05:17+09:00 Subject: Re: Help with a regexp Hi -- On Sat, 15 Jul 2006, Daniel Martin wrote: > Logan Capaldo writes: > >> On Jul 14, 2006, at 2:16 PM, dblack@wobblini.net wrote: >> >>> Is ??{ code } in Perl different from #{...} in Ruby? (Not that I was >>> able to solve Daniel's problem with #{...}, but I'm just curious about >>> the comparison.) >> > >> >> I apologize to any perlers if this isn't idiomatic (or clean) perl, I >> never had to use this kind of magic in my perl days and I had >> difficulty getting it to work when I stored the regexp in a variable. >> But the point is, is that it does work. Which is kind of scary. > > I think you probably had trouble with the \ when you tried storing it > in a variable because of quoting issues. So use qr, the perl > equivalent of ruby's %r: > > $s1 = "3:abc"; > $s2 = "24:abc"; > > $regexp = qr/(\d+):(??{'\w{' . $1 . '}'})/; > > print "Good\n" if ( $s1 =~ $regexp); > print "Bad\n" if ( $s2 =~ $regexp); > > Although, since bencoded strings can contain any character, and not > just word characters, what you really want is: > > $regexp = qr/(\d+):(??{".{$1}"})/; > > Perl allows bunches of special constructs in regular expressions that > sane languages, which like to keep the matching of regular expressions > away from being able to jump back into the host language. (Note that > perl combines this feature with extra language-level security support, > since most programmers would assume that a user-supplied regexp > couldn't execute arbitrary code) Ruby does let you jump back, though, with #{...}. But it looks like Perl does an extra level of compilation. (Unless I've got that backwards.) David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy http://www.manning.com/black => RUBY FOR RAILS (reviewed on Slashdot, 7/12/2006!) http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log dblack@wobblini.net => me