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

Dear Perlmonkers, I'm trying to get the index of the last occurence of a character inside a string. I have a solution that goes like this:
#!/usr/bin/perl use strict; use warnings; my $text = 'abcd@efgh@ijk@lmn@opq@rst'; my $str_index = length($text) -1 - index( reverse( $text ), '@', 0 ); print "str_index: $str_index\n";
It's working ok, but I wonder if there aren't better/nicer ways to do it.

Thanks!

Krambambuli

Replies are listed 'Best First'.
Re: Index of the last occurence of a character inside a string
by dHarry (Abbot) on Aug 06, 2008 at 09:47 UTC

    Have you thought about using rindex?

      Slap on my head! :)

      No, I have completely forgotten about rindex (if I ever knew, that is - I don't think I've ever used it so far.)
      Thank you!

      Krambambuli
Re: Index of the last occurence of a character inside a string
by FunkyMonk (Bishop) on Aug 06, 2008 at 09:47 UTC
    There's a function to do just that: rindex


    Unless I state otherwise, all my code runs with strict and warnings
Re: Index of the last occurence of a character inside a string
by ambrus (Abbot) on Aug 06, 2008 at 11:55 UTC

    As posters have already said, rindex will work, but there are also regexen.

    my $needle = '@'; my $str_index = $text =~ /.*()\Q$needle\E/ && $-[1];