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

All, How are you.
I would like to get the position which has the same value in the array.

@data = ( orange, strawberry, apple, orange, banana);


I want to get the following output.
"$data[0] and $data[3] has a same value!!"
Let me know how to do it.
Thanks in advance, EJ

Edited by Chady -- added code tags.

Replies are listed 'Best First'.
Re: How do I get the position of the same value in array or list.
by pelagic (Priest) on Apr 07, 2004 at 06:45 UTC
    #!/usr/bin/perl use strict; my %position; my @data = ( qw[orange strawberry apple orange banana orange apple coc +onut] ); my $pos = -1; foreach my $item (@data) { ++$pos; push (@{$position{$item}}, $pos); } foreach my $foo (keys %position) { if (scalar @{$position{$foo}} > 1) { print "$foo occurs on positions @{$position{$foo}}\n"; } } __OUTPUT__ apple occurs on positions 2 6 orange occurs on positions 0 3 5 END__OUTPUT__

    pelagic
    -------------------------------------
    I can resist anything but temptation.
Re: How do I get the position of the same value in array or list.
by matija (Priest) on Apr 07, 2004 at 06:47 UTC
    foreach (@data) { push(@$pos{$_},$i++); } foreach (keys %pos) { if ($#{$pos{$_}) { print join(" and ",map("\$data[$_]",@$pos{$_}))," have the same +value: $_\n"; } }
    First create a HoA, keys of the hash are the values from the array @data, and the arrays contain the indices in @data where each data can be found.

    Then just print those keys where the size of the list of indices is more than 1.

    Due to the nature of the way we fill the HoA, there won't be any empty lists (Otherwise I'd have to be carefull of the $#==-1 case.)

Re: How do I get the position of the same value in array or list.
by Zaxo (Archbishop) on Apr 07, 2004 at 06:41 UTC

    A hash will help,

    my %hsh; push @{$hsh{$data[$_]}}, $_ for 0..$#data; for (keys %hsh) { printf '$data[%d] and $data[%d] have the same value!!', @{$hsh{$_}} if @{$hsh{$_}} == 2; }
    %hsh becomes a Hash-of-Arrays with push, then we just look for arrays bigger than 1. I restricted that to 2 for the example.

    Update: tinita++, corrected.

    After Compline,
    Zaxo

      Zaxo, you mean the right thing, but it should be @{ $hash{key} } instead of @$hash {key}, so:
      push @{ $hsh{$data[$_]} }, $_ for 0..$#data;