in reply to char. VS char.

While tr/// will do the replace, i thought i should comment on the idea of an array being used. If you are keeping track of a one-to-one relationship, a hash is the best solution.
People new to perl often don't use hashes, but a quick example would be :
my %hash = ( A => W, B => R, C => T, ); my $letter = 'A'; print "Letter : $letter\n"; ## prints "Letter : A" print "Letter : $hash{$letter}\n"; ## prints "Letter : W"
just figured to hit the problem where you are already working on it, rather than going with tr/// and having you work out the complex array solutions for your next project (which i did as a newbie)
can't sleep clowns will eat me
-- MZSanford

Replies are listed 'Best First'.
Re: char. VS char.
by marcus (Scribe) on Aug 30, 2001 at 16:32 UTC
    I agree, hashes seem to be more appropriate for this kind of thing, I've whipped up a generic sub here that seems to be a little more in tone with what the original poster requested:

    #!/usr/bin/perl -w use strict; #always sub myencode { my ($sentence,$encodehash)=@_ or die "not enough parameters for enco +de:@_"; foreach my $key (keys %$encodehash) { $sentence =~ s!$key!$$encodehash{$key}!g; } return $sentence; } my %encoding=("A"=>"D","B"=>"E","C"=>"F"); print myencode("ABC",\%encoding);

    qw[marcus]