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

I have two arrays of equal length

@a= [a,b,c,b,b,c,a,a] @b= [a,a,b,c,c,a,b,c]
Id like to create a new array, @c, based on a set of rules based on all the possible matchings of the elements in @a and @b ;

@a=aaabbbccc @b=abcabcabc @c=xyzrstmno
for example, if $a[]=a and $b[]=a then $c[]=x.

Im guessing the use of map and a hash to assign the rules but cant work out the specifics.

Thanks in advance for any ideas.

Replies are listed 'Best First'.
Re: recode 2 strings into 1
by GrandFather (Saint) on Feb 27, 2009 at 00:30 UTC

    No map required, but a hash sure helps:

    use strict; use warnings; my @arg1 = split '', 'aaabbbccc'; my @arg2 = split '', 'abcabcabc'; my @result = split '', 'xyzrstmno'; my %rules; die "Mismatched lengths in input arrays" if @arg1 != @arg2 or @arg1 != @result; # Build the rules hash $rules{$arg1[$_]}{$arg2[$_]} = $result[$_] for 0 .. $#result; # Do da deed my @test1 = qw(a b c b b c a a); my @test2 = qw(a a b c c a b c); print "$test1[$_]:$test2[$_] = $rules{$test1[$_]}{$test2[$_]}\n" for 0 .. $#test1;

    Prints:

    a:a = x b:a = r c:b = n b:c = t b:c = t c:a = m a:b = y a:c = z

    True laziness is hard work
Re: recode 2 strings into 1
by olus (Curate) on Feb 26, 2009 at 23:57 UTC
Re: recode 2 strings into 1
by bichonfrise74 (Vicar) on Feb 27, 2009 at 00:34 UTC
    Can you try something like this?
    #!/usr/bin/perl use strict; my @a = qw( a b c b b c a a ); my @b = qw( a a b c c a b c ); for (my $i = 0; $i <= $#a; $i++ ) { &Results( $a[$i] . $b[$i] ); } sub Results { my $input = shift; my $result = { 'aa' => 'result_1', 'ba' => 'result_2', }; print "Input: $input --- Result: $result->{$input}\n"; }