On Dec 16, Jan Eden said:
>>#!perl
>>
>>%enctabelle = (...);
>>
>>my $re = '(' . join('|', map quotemeta($_), keys %enctabelle) . ')';
>>$re = qr/$re/;
>>
>>while (<>) {
>> s/$re/$enctabelle{$1}/g;
>> print;
>>}
Let me explain this for you, and fix it, too.
# this produces 'key1|key2|key3|...'
my $re = join '|',
map quotemeta($_), # this escapes non-alphanumberic
# characters;
sort { length($b) <=> length($a) } # sorts by length, biggest first
keys %enctabelle; # the strings to encode
What this does is put the keys in a string, separated by a | (which means
"or" in a regex), quotemeta()d (which ensures any regex characters in them
are properly escaped), and ordered by length (longest to shortest). That
last part is important: if you have keys 'a' and 'ab', you want to try
matching 'ab' BEFORE you try matching 'a', or else 'ab' will NEVER be
matched.
Then, we take $re, and turn it into a compiled regex:
$re = qr/($re)/;
The qr// operator (in perlop) gives you a compiled regex; it's good for
efficiency in certain situations (although this isn't really one of them).
$text =~ s/$re/$enctabelle{$1}/g;
That replaces all keys with their values.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
<stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
[ I'm looking for programming work. If you like my work, let me know. ]
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>