in reply to Re: Matching a truncated word
in thread Matching a truncated word

Hopefully this isn't too obfuscated. I've tried to restrain myself here. The trunc_match function creates a regular expression for any given input string, and should handle wierd stuff to by virtue of the qr() operator.
sub trunc_match { my ($what) = @_; my @bits; for (1..length $what) { push (@bits,$what); chop $what; } return '('.join ('|', map { quotemeta($_) } @bits).')$'; } my $rx = trunc_match ("foobar"); $_ = "This sentence ends in foob"; if (/$rx/) { print "Truncated, ends in '$1'\n"; }
The format of the regex is something like:
(foobar|fooba|foob|foo|fo|f)$
So you get whatever you're looking for in $1, or the returned array if you're brave enough to use /g.

Update:
For some reason, I had confused qr with quotemeta, and so I am updating the code here to be more sensible in that regard. Thanks, once again, Hofmator.

Replies are listed 'Best First'.
Re: Re^2: Matching a truncated word
by John M. Dlugosz (Monsignor) on Aug 01, 2001 at 01:33 UTC
    That's an interesting use of qr// to escape out the individual parts, instead of using logic involving \Q..\E. I like the idea, since it avoids the confusion of escape chars in strings vs. in regex, and multiple levels of escaping. I'll be sure to remember that.