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

Hello Monks, Iam new to programming in perl.I have a question. If there are two arrays of strings and the elements of second array have there position interchanged with respect to the 1st array. Is there a way to compare the strings in the arrays and assign numerical values to strings of each array such that i can output the numerical values based on the position of strings in arrays1 and arrays2. For ex: if array1=("a,b,c,d,e") and array2 =("a,c,d,e,b").How can we output pos1=(1,2,3,4,5) and pos2=(1,3,4,5,2)using arrays or hash arrays?. Thanks in advance.
  • Comment on Assign values by position to strings in two arrays

Replies are listed 'Best First'.
Re: Assign values by position to strings in two arrays
by almut (Canon) on Apr 26, 2009 at 20:51 UTC

    For example:

    my @array1 = qw(a b c d e); my @array2 = qw(a c d e b); # assign numbers and create lookup table my $i; my %pos1 = map { $_ => ++$i } @array1; # lookup items of array2 my @pos2 = map $pos1{$_}, @array2; print "@pos2\n"; # 1 3 4 5 2

    The hash %pos1 maps strings to numbers, i.e. you can lookup the number associated with for example "a" by writing $pos1{a}, which would give 1 here.

    (If items can occur more than once in array1 (i.e. not unique), you'd have to define how to deal with that case...)