fatfinger has asked for the wisdom of the Perl Monks concerning the following question:

I have a list of many numbers that need to be transliterated. In short I would like to translate each number in the list to a corresponding number for example: "1" needs to become "567898", "2" needs to become "543267", "3" needs to become "234565", "4" needs to become "987654", and so on...... Any ideas on how this can be done ? Thanks for your time.

Replies are listed 'Best First'.
Re: Convert a number to another number?
by Fletch (Bishop) on Sep 16, 2008 at 16:46 UTC
    • Create a hash containing your mapping.
    • Look up the source number and replace with the value from the hash as you process the input.
    • Profit!

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      "Profit!"

      Yeah; I hope OP will apply the result to my $cash!

Re: Convert a number to another number?
by toolic (Bishop) on Sep 16, 2008 at 16:50 UTC
    Use a hash:
    use strict; use warnings; my %lookup = ( 1 => 567898, 2 => 543267, ); my @test = qw(0 a 2 1); for (@test) { print exists $lookup{$_} ? $lookup{$_} : $_, "\n"; } __END__ 0 a 543267 567898

      In the TMTOWTDI spirit, if your keys are really going to be "1", "2", "3", "4", and so on, you can use an array:

      my @lookup; @lookup[1..4] = ( 567898, 543267, 234565, 987654, ); my @test = qw(0 a 2 1); for (@test) { print defined $lookup[$_] ? $lookup[$_] : $_, "\n"; }
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Convert a number to another number?
by MidLifeXis (Monsignor) on Sep 16, 2008 at 20:27 UTC

    This also looks like it could be a beginning programming assignment. Please show what you have done so far, and if it is homework, identify it as such.

    Monks are not against helping you with a homework problem, they are just against doing your homework for you.

    --MidLifeXis

Re: Convert a number to another number?
by mr_mischief (Monsignor) on Sep 16, 2008 at 18:45 UTC
    You have good explanations for how to accomplish what you asked about already. Without you telling us, though, I wonder why you need to do this.

    What I see resembles the basis for a simple substitution cipher, which is not a very secure form of encryption. If securing data cryptographically is what you're trying to do you may find that asking about encryption techniques or modules that implement them might be more fruitful.

Re: Convert a number to another number?
by dwm042 (Priest) on Sep 16, 2008 at 20:12 UTC
    #!/usr/bin/perl use warnings; use strict; # # hashes are superb for translations # my %translate = ( 1 => 567898, 2 => 543267, 3 => 234565, 4 => 987654 ); my @data = ( 1, 2, 3, 4 ); for my $data (@data) { print $data, " => ", $translate{$data}, "\n"; }
    And the output is:

    C:\Code>perl translate.pl 1 => 567898 2 => 543267 3 => 234565 4 => 987654