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

Is there a way to return an array's element number when searching with ~~ smart match operator?
if ($a ~~ @array){print "$a is part of @array"} ??? print "The $a is $i element of the @array"
Is it possible at all or should I just try to use foreach loop instead the smart match operator? Thanks!

Replies are listed 'Best First'.
Re: Smart match operator question
by toolic (Bishop) on Aug 29, 2011 at 16:13 UTC
    I don't know if smart match can do this, but you could consider List::MoreUtils:
    use warnings; use strict; use List::MoreUtils qw(firstidx); my @list = (1, 4, 3, 2, 4, 6); printf "item with index %i in list is 4\n", firstidx { $_ == 4 } @list +; __END__ item with index 1 in list is 4
Re: Smart match operator question
by Anonymous Monk on Aug 30, 2011 at 08:49 UTC

    No, smart match operator cannot do this. I thought, maybe, you could use the return value, but no, you can't, the return value of smart match operator is boolean (true/false).

    My test code

    $ perl -E " my( $r, $a, @bba ) = ( 0, 1, 2..4,1,2..4 ); $r = $a ~~ @b +ba; say $r; " 1

    You could accomplish this task by way of overload

    #!/usr/bin/perl -- use 5.010; use strict; use warnings; my @array = ( 2..4,6,2..4 ); say "@array"; my $r = 6 ~~ bless\@array,'smart::ix'; say "$r $$r = $array[$$r]"; BEGIN { package smart::ix; use overload '~~' => \&rix; sub rix { my( $self, $val, $selfOnRight ) = @_; my $ix = 0; while( $ix <= @$self ){ return \$ix if $val ~~ $self->[$ix]; $ix++; } return ; } $INC{'smart/ix.pm'} = __FILE__; 1; } __END__ 2 3 4 6 2 3 4 SCALAR(0x9b386c) 3 = 6
    This could make a good feature, say use feature 'smarter'; makes ~~ return an object, and sets the global variable $s (for smart) to the same value (like sort does for $a and $b), and ->ix returns the index (for this use case), or ->matches for the general case ....

    Hmm, now that I think about, after consulting http://search.cpan.org/~jesse/perl-5.14.1/pod/perlsyn.pod#Smart_matching_in_detail some more, ~~ seems rather limited , oh well

      Personally I would prefer to see index implemented to work on a list, as well as a string.
        Now thats thinking! Should be trivial to implement.