in reply to find position of element of array

Can't believe this hasn't been pointed out yet, but @array = {"a", "b", "c", "d"} leaves @array with one element, that element being a hashref. You want parentheses instead of braces.

Instead of the grep solution offered above, you can use List::Util's first.

#!/usr/bin/perl -l use List::Util "first"; my @array = qw(a b c d); my $index = first { $array[$_] eq "c" } 0..$#array; die "c was not found in \@array" if ! defined $index; print $array[$index-1];

Replies are listed 'Best First'.
Re^2: find position of element of array
by perlbeginner10 (Acolyte) on Nov 13, 2005 at 11:38 UTC
    Hi Guys, I tried this code. At first I thought it was working fine. But now I see that there is a small problem with this code. The problem is : the index is circular (semi circular I guess). That means, if my array is @a = {"a", "b", "c", "d", "e"} and I want to find the element before "a", it should be undefined. But when I print the element before "a" using the above method and (defined $array$index -2), I get "e". Also, it is strange that when I check like: if (defined $array$index +2), that element is correctly not defined. If you understand this problem, please help me out. Thanks

      Just check for the returned index being 0 and handle that special case appropriately. Negative indexes count backwards, so in your above array $a[-1] will correctly return "e". $a[5] will be undef, because the array only contains values for @a[0..4]. Take a look at perldoc perldata for more details on arrays.

      BTW, you should add <code></code> tags around the code in your posts, otherwise it comes out mangled.


      Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan
        Thanks a lot... I will do as you say.