Re: Converting using a hash
From: Jeff 'Japhy' Pinyan (japhy_at_perlmonk.org)
Date: 12/17/03
- Next message: Drieux: "Re: Out of memory error problem"
- Previous message: R. Joseph Newton: "Re: script for passwd file"
- In reply to: Jan Eden: "Converting using a hash"
- Next in thread: Jan Eden: "Re: Converting using a hash"
- Reply: Jan Eden: "Re: Converting using a hash"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 16 Dec 2003 20:36:39 -0500 (EST) To: Jan Eden <lists@jan-eden.de>
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 japhy@pobox.com http://www.pobox.com/~japhy/ RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/ <stu> what does y/// stand for? <tender***> why, yansliterate of course. [ I'm looking for programming work. If you like my work, let me know. ]
- Next message: Drieux: "Re: Out of memory error problem"
- Previous message: R. Joseph Newton: "Re: script for passwd file"
- In reply to: Jan Eden: "Converting using a hash"
- Next in thread: Jan Eden: "Re: Converting using a hash"
- Reply: Jan Eden: "Re: Converting using a hash"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]